Monday, October 8, 2018

Promise example in Angular 6

A Promise is a way to execute asynchronous operations. A Promise can give 2 possible results a success response or a failure error message. The most common usage of promises is to make API calls to services to get data. Let us see on how to make async calls using promises to get data and display it in UI using Angular.

The Angular HttpClient library by default gives an Observable, for the sake of this example we will convert the Observable to a Promise and use it in the Component to display the results from the API call.

Let us extend our previous Service example, let us start by adding a new service userdata.service using the ng generate command as follows.

ng generate service userdata

In the service file add the following code.

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

@Injectable({
  providedIn: 'root'
})
export class UserdataService {
  constructor(private http: HttpClient) { }
    getUsersPromise() {
      return this.http.get('https://jsonplaceholder.typicode.com/users')
          .toPromise()
          .then(res => res)
          .catch(err => {
              return Promise.reject(err.json().error  || 'Server error');
          });
    }
}

Notice that we are using toPromise() to convert the default Observable to a Promise.
Next we will have to include HttpClient in the app module so that we can use in the service.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Next we have to inject the new data service in our app component and invoke the Promise to get data from the API.

import { Component } from '@angular/core';
import { UserdataService } from './userdata.service';
import { HelloService } from './hello.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userList;
  errorMessage: string;
  constructor(private svcData: UserdataService, private svcHello: HelloService) { }
  title = 'Angular 6';
  message = this.svcHello.getMessage();

  ngOnInit() {
    this.getDataPromise();
  }

  getDataPromise() {
    this.svcData.getUsersPromise()
    .then(response => {
        this.userList = response;
      },
      error =>  {
        console.error('An error occurred in retrieving User list.', error);
      });
  }
}

In the components code we use the promise in a function getDataPromise(), notice that we call this function in the ngOnInit() lifecycle hook. ngOnInit will be called when the component loads, hence this in a good place to make the API call and get the data ready to display it in the component.

Finally we will modify the components template file to display the data from the Promise. Since our promise returns an array of user details, we will add a *ngFor loop in the component and display the list of users.
<div style="text-align:left">
  <p class="title">Welcome to {{ title }}!</p>
  <p class="msg">Message from Service:  {{ message }}!</p>
  <p>Data from Promise</p>
  <ul>
    <li *ngFor="let user of userList"> 
      {{ user.name }} - {{ user.email }}
    </li>
  </ul>
</div>

Finally the output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: