Promise, in Javascript, is a concept which allows the callee function to send back a promise (sort of assurance) to the caller function that it would, for sure, send back a resolution, be it a success or a failure at a little later point of time. The caller believes the callee if a promise is sent back, and, proceeds ahead with the program execution.
On a lighter note, the following comic strip represents the relationship between the caller and callee. As like the below, caller function can believe on callee function sending back Javascript promise object, which does result in the state of either resolution or a rejection (in case of errors).
In this post, you will learn about some of the following concepts in relation to promise concept vis-a-vis an angular app built with Angular 2.*, Angular 4.* and Angular 5.* versions:
Here is a detailed introduction of promise concept with the help of code examples wherever appropriate:
function printHelloWithPromise(name) { let promise = new Promise(function(resolve, reject) { // In place of the code given below, one can call REST APIs // For errors, one can choose to reject the promise; // For successful processing, promise can be resolved // const responseVar = 1+1; if(responseVar == 2) { resolve("Success: " + name); } else { reject("Error: " + name); } }); return promise; }
Note some of the following:
let greetingPromise = printHelloWithPromise("https://vitalflux.com"); greetingPromise.then(function(resolveOutput) { console.log(resolveOutput); }, function(rejectOutput) { console.log(rejectOutput); });
Note some of the following:
In this section, you will learn the usage of Promise with Angular Http service. The code given below works for Angular 2 and Angular 4 apps.
The following represents the code of a custom Angular Service. The code has an API namely getRx. The getRx API internally invokes a REST API call to get the prescription information from the server for a logged in user.
import {Http, Headers} from '@angular/http'; import {Injectable} from '@angular/core'; import {Rx} from './rx'; import {Cookie} from 'ng2-cookies'; @Injectable() export class RxService { private rxUrl = 'http://localhost:8080/rx'; constructor(private http: Http) { } getRx(): Promise<Rx[]> { let headers = new Headers({ 'Content-type': 'application/json', 'Authorization': 'Bearer ' + Cookie.get('access_token') }); return this.http.get(this.rxUrl, {headers: headers}) .toPromise() .then(res => res.json()) .catch(err => { return Promise.reject(err.json().error || 'Server error'); }); } }
Make a note of some of the following in above code:
The code below represents the processing of callee method which returns Promise<Rx[]>.
export class RxListComponent implements OnInit { rxlist: Rx[]; errorMessage: string; constructor(private rxService: RxService, private router: Router) { this.errorMessage = ''; } ngOnInit(): void { this.getRx(); } getRx() { this.rxService.getRx() .then(rxlist => { this.rxlist = rxlist; if (this.rxlist.length === 0) { this.errorMessage = 'There are no prescriptions you have created so far!'; } }, error =&gt; { this.router.navigateByUrl('/auth/login'); console.error('An error occurred in retrieving rx list, navigating to login: ', error); }); } }
In this section, you will learn the usage of Promise with Angular HttpClient service. The code given below works for Angular 4.3 and Angular 5 apps. Note that HttpClient is the recommended way for communicating with remote APIs from Angular 5.* onwards.
Make a note of some of the following in the code given below:
import {Http, Headers, RequestOptions} from '@angular/http'; import {Injectable} from '@angular/core'; import {Rx} from './rx'; import {Observable} from 'rxjs/Observable'; import {Cookie} from 'ng2-cookies'; import {HttpClient, HttpHeaders, HttpResponse} from "@angular/common/http"; @Injectable() export class RxService { private rxUrl = 'http://localhost:8080/rx'; constructor(private httpClient: HttpClient) { } getRx(): Promise<Rx[]> { return this.httpClient.get(this.rxUrl, {observe: 'response', headers: new HttpHeaders().set('Authorization', 'Bearer ' + Cookie.get('access_token'))}) .toPromise() .then(this.extractData) .catch(err => { return Promise.reject(err.error || 'Server error'); }); } extractData(res: HttpResponse<Object>) { var array = new Array(); var key, count = 0; for(key in res.body) { array.push(res.body[count++]); } return array; } }
[wp_quiz id=”6419″]
In this post, you learnt about some of the following:
Did you find this article useful? Do you have any questions about this article or understanding Promise and related concepts and terminologies vis-a-vis Angular 4/Angular 2 Http APIs and Angular 5 HttpClient APIs? Leave a comment and ask your questions and I shall do my best to address your queries.
In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…
Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…
With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…
Anxiety is a common mental health condition that affects millions of people around the world.…
In machine learning, confounder features or variables can significantly affect the accuracy and validity of…
Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…