Creating News Application With Ionic 4 and Angular

Creating News Application With Ionic 4 and Angular

In this tutorial we’ll be using Ionic 4 to build a news application that makes use of a third-party .Ionic 4 is the latest version of Ionic, a mobile framework originally built on top of Cordova and Angular.

Ionic 4 is the latest version of Ionic, a mobile framework originally built on top of Cordova and Angular. Ionic allows users to create hybrid mobile apps with HTML, CSS and JavaScript and their related web technologies.

What makes Ionic 4 the best version yet is that it’s now framework agnostic. This means it’s not dependent on Angular anymore, and you you’ll be able to use it with any framework or library you are familiar with, or with plain JavaScript.

But at the time of this writing, Ionic CLI only supports generating Ionic projects based on Angular, so we’ll be using an Angular/Ionic project to build our news application.

See a hosted version of the application we’ll be building and grab the source code from this GitHub repository.

Prerequisites

Let’s get started with the prerequisites you need to be able to follow this tutorial comfortably.

  • You will need to have Node.js and npm installed on your development machine. If that’s not the case, the simplest approach is to go to the official website and grab the binaries for your system. Node.js is not a requirement for Ionic itself, but for Ionic CLI (and Angular CLI behind the scenes) which is the tool that we’ll be using to generate Ionic projects.
  • We’ll be using Ionic with Angular, which is based on TypeScript, so you need to be familiar with the basic concepts of TypeScript.
Installing Ionic CLI 4

Ionic CLI 4 is the latest version of the CLI. Open a terminal and run the following command to install it on your system:

$ npm install -g @ionic/cli

Please note that you may need to add sudo before your command in order to install the package globally if you’re using a Debian-based system or macOS. For Windows, if you get any permission errors you can use a command prompt with administrator access. In all systems, you can avoid the npm permission errors by either reinstalling npm with a node version manager (recommended) or manually changing npm’s default directory. See the docs.

Next, you can generate a project based on Angular by running the following command:

$ ionic start

The CLI will interactively ask you for the necessary information about your project, such as the name (Enter newsapp or whatever name you prefer) and the starter template (choose sidemenu which will give you a starting project with a side menu and navigation of the box).

Next press Enter to instruct the CLI to start generating the files and installing the dependencies from npm.

Finally the CLI will ask you if you want to Install the free Ionic Appflow SDK and connect your app? (Y/n). You can type n if you don’t want to integrate the cloud services offered by Ionic.

Appflow is a continuous integration and deployment platform for Ionic developers. Appflow helps developers continuously build and ship their iOS, Android, and web apps faster than ever. You can find more information about Appflow from the official docs.

Next, you can navigate to your project’s root folder and run the following command to start a live-reload development server:

$ cd ./newsapp
$ ionic serve

Your application will be available from the http://localhost:8100 address.

This is a screenshot of the application at this point:

You can see that we already have a pretty decent starting application without doing any development yet. Let’s make some changes to our project.

The project already has two pages — home and list. Leave the first page and delete the list page.

First, remove the src/app/list folder. Next, open the src/app/app-routing.module.ts file and remove the route entry for the list page:

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    loadChildren: './home/home.module#HomePageModule'
  },
  {
    path: 'list',
    loadChildren: './list/list.module#ListPageModule'
  }
];

We have three routes, one for the empty path that redirects to the /home route, the /home route that displays the home page, and the /list route that displays the list page. You simply need to remove the last object.

You also need to remove the link for the list page from the side menu. Open the src/app/app.component.ts file. Locate the appPages array defined in the component:

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: 'home'
    },
    {
      title: 'List',
      url: '/list',
      icon: 'list'
    }
  ];

And simply remove the second object: { title: 'List', url: '/list', icon: 'list'}.

Now, let’s create an about page for our application. In your terminal, run the following command:

$ ionic generate page about

This command will generate a src/app/about folder with a bunch of files, and will update the src/app/app-routing.module.ts file to include a route for the generated page:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    loadChildren: './home/home.module#HomePageModule'
  },
  { path: 'about', loadChildren: './about/about.module#AboutPageModule' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Let’s add a link to the about page in the side menu. Open the src/app/app.component.ts file and update the appPages array:

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: 'home'
    },
    {
      title: 'About',
      url: '/about',
      icon: 'help-circle-outline'
    }
  ];

This is a screenshot of the menu at this point:

Next, open the src/app/about/about.page.html and add a menu icon to the toolbar of the page, which allows users to open the side menu:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      About
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

</ion-content>

Now let’s add some theming to our application UI.

Open the src/app/about/about.page.html and add a primary color to the menu toolbar and a dark color to the content section:

<ion-header>
  <ion-toolbar color="primary">
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      About
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content color="dark" padding>
<p>
  This is a news app built with Ionic 4 and the <a href="https://newsapi.org/">News API</a>
</p>
</ion-content>

This is a screenshot of the page:

Next, let’s theme the homepage. Open the src/app/home/home.page.html file and replace its contents with the following:

<ion-header>
  <ion-toolbar color="primary">
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      Home
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content color="primary">
    <ion-card>
      <ion-card-header>
        <ion-card-subtitle>Welcome to our News App</ion-card-subtitle>
      </ion-card-header>
      <ion-card-content>
        <p>
          Enjoy the latest news from TechCrunch. 
        </p>
        <ion-spinner *ngIf="!articles"  name="dots"></ion-spinner>
      </ion-card-content>
    </ion-card>
</ion-content>

Next, open the src/app/home/home.page.scss file and add:

ion-card{
  --background: #021b46;
  --color: #fff;
}

Also, open the src/app/app.component.html file and add a primary color to the menu toolbar:

        <ion-toolbar color="primary">
          <ion-title>Menu</ion-title>
        </ion-toolbar>

Getting News Data

Let’s now see how you can retrieve news data from the third-party news API available from NewsAPI.org/, which offers a free plan for open source and development projects.

You first need to head here to register for an API key:

Fill the form and submit it. You should get redirected to the page where you can copy your API key:

Adding a Service

Next, let’s create a service that will take care of getting data from the news API. In your terminal, run the following command:

$ ionic generate service api

Next, open the src/app/app.module.ts file then import HttpClientModule and add it to the imports array:

// [...]
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    // [...]
    HttpClientModule,
  ],
  // [...]
})
export class AppModule {}

Next, open the src/app/api.service.ts file and inject HttpClient via the service constructor:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private httpClient: HttpClient) { }
}

Next, define an API_KEY variable which will hold your API key from the News API:

export class ApiService {
  API_KEY = 'YOUR_API_KEY';

Finally, add a method that sends a GET request to an endpoint for TechCrunch news:

  getNews(){
    return this.httpClient.get(`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`);
  }

That’s all we need to add for the service.

Open the src/app/home/home.page.ts file and import, then inject, ApiService via the component constructor:

import { Component } from '@angular/core';
import { ApiService } from '../api.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  constructor(private apiService: ApiService){}
}

Next, add an articles variable that will hold the retrieved news:

export class HomePage {
  articles;

Add an ionViewDidEnter() method, where you call the getNews() method of ApiService to retrieve the news:

  ionViewDidEnter(){

    this.apiService.getNews().subscribe((data)=>{
      console.log(data);
      this.articles = data['articles'];
    });
  }

Finally, let’s iterate through the articles variable and display the news on our homepage.

Again, open the src/app/home/home.page.html file and add the following code:

  <ion-card *ngFor="let article of articles">
    <ion-img src="{{article.urlToImage}}"></ion-img>
    <ion-card-header>
      <ion-card-subtitle>{{article.title}}</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
      <p>
        {{article.description}}
      </p>
      <ion-button ion-button fill="outline" href="{{article.url}}" large>Read full article</ion-button>

    </ion-card-content>
  </ion-card>

We simply use the ngFor directive to loop through the articles variable and display the image, title, description and URL of each article inside a card component.

This is a screenshot of the result:

You can either host this application on the web (as a PWA) or build it and publish it on the app stores. You can find a live version from this link and the source code in this GitHub repository.

Conclusion

We’ve built a news application from scratch with Ionic 4 and Angular. The application still has plenty of room for improvement, so feel free to play with it and extend it on your own. For example, you could add sources other than TechCrunch, and allow the user to select the source of the news.

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

AngularJS Development - Why Choose AngularJS For Web Development?

AngularJS Development - Why Choose AngularJS For Web Development?

AngularJS is the most popular framework for web development and nowadays more in demand. We explain in-details why choose AngularJS for web development for your next project?

AngularJS is a web development framework based on open script languages like JavaScript, hypertext markup language and cascading style sheet.
Web development has become an integral part of the marketing world over a period of time. We can't imagine the marketing world without advertisement that is framed virtually or shopping webpage which had made the life of people so much easier.
So, designing a webpage that gives good user experience and has flexible applications are the current requirements of the marketing world.
AngularJS development company has been revolutionary in the web development field. Web developers are constantly utilizing AngularJS to build a vibrant and flexible application.

Here, we would be going through a certain point which would be acknowledging the fact as to why AngularJS should be utilized in web development.
It is one of the most popular web development applications. So, let's glance over certain points. Why?
Certain problems that are tackled by the AngularJS
Imaging, where you are interrupted every time you select a different task on a webpage because the page is refreshed automatically every time. So, this process becomes kinda tedious and most-importantly time-consuming.
This problem is eradicated with the use of AngularJS.
The master language that is utilized by AngularJS as a default language is HTML.
The AngularJS has the ability to support a wide array of functions. A variety of functions can be created on AngularJS without any issues of support. And secondly, it offers certain additional features as well like dependency injection, simple architecture, convenient testing, and parallel development.

1. High Performance
Robustness of web development is what sets this feature apart.
It is powered with a wide horizon of features like filters, data binding, animations, API, scope management, clients, directives, form validation, content sanitation and many more.

2. User Interface
As I have stated earlier the master language that has been set as a default language for AngularJS is HTML.
So, this language creates a good user interface. So, it has automatically sorted one of the biggest hurdles faced during web development which is designed user-friendly flexible apps.

3. Data Binding
Changes made in the modules are quite highlighting in it. So, these features make it more dependable in the market.

4. Filters
They are an integral member or part of any data development features. This added feature helps in creating variations in the web application.
For example, you can use uppercase and lowercase features while present large data to the user.

5. Use Of MVC
AngularJS makes use of features like MVC for the purpose of web application development. MVC stands for the model view controller.
Now, if we break down MVC into three segments that it would be quite easier to understand it. The first segment that is taken into consideration is model designing where all the work related to model development and maintenance is carried out.
Second is the view portion where its sole purpose is only to view the data. And the last segment is the controlling portion which is a linking string between the two components.

6. Testing
It is an important step in any web application development process.
So, the employment of the AngularJS web application, web development has made it quite efficient. It comes with a set of unit test runners that carry out the testing procedure at each and every step of the web development process.
So, it gives you can approximate rough idea as to how the web application is going to perform in the near future.

So, these features set the AngularJS web development application apart from the others. No doubt, it is one of the most demanded web development applications present in the market out there.
Well, if you are a newbie in the web development arena, then you don't have to stress over the fact. There are certain web developers companies that can assist you in the web development process using AngularJS web development.

7. Declarative Code Style
Declarative paradigm is mainly utilized in AngularJS to create patterns while building a web application program.
The main purpose of using declarative code style is to make program code easier, lightweight and decipherable.
Spa features of AngularJS
Validation capabilities are provided along with the AngularJS.
It handles the error-handling issues with its validation capabilities.

8. Easy To Use
With the horde of features provided by the AngularJS, it becomes easy to use.
And because it uses the MVC model in its web development procedure hence it becomes quite easy to use. It minimizes the need to write the code. Secondly, it has an extensible feature as well where HTML can be turned into XML, which makes it more demandable.

Read also: 10 Advantages of AngularJS Development Services for Enterprise

9. Use Of Directives
Whenever you want to make logistics in the web development, you can always opt for this added feature in the AngularJS. It improves code readability.
So, one could always seek out for AngularJS development services to get their work done without any hassle.