Promise, in Javascript, allows an asynchronous operation to happen in the sense that caller function getting promise object returned by callee function proceeds ahead with the program execution. And, upon the return of promise object, the processing continues. The Promise concept can be used with Angular Http service to achieve asynchronous data retrieval from the server using GET API. The code example in this article applies to both Angular 2 and Angular 4.
On the lighter side, here is a comic strip on whether Promises are kept or not :). In Javascript, promises go from state of “pending” to “resolution” or “rejection”.
In this post, you will learn about some of the following in relation to using promise concept vis-a-vis an Angular 4 or Angular 2 Http Service:
In this section, you will learn the usage of Promise with Angular Http service (Get API).
The following represents the code of a custom Angular Service making use of Http service for making REST API call. The code given below has an API namely getRx. The getRx API internally invokes a REST API call over Http 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 returned Promise<Rx[]> in caller method. Make a note of usage of then function.
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 => { this.router.navigateByUrl('/auth/login'); console.error('An error occurred in retrieving rx list, navigating to login: ', error); }); } }
[wp_quiz id=”6385″]
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 the usage of Promise with Angular Http service (Get API)? 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…
View Comments
In Practice test, the third question - "Which of the following needs to be invoked to convert Observable into a Promise object?" Both promise() or toPromise() will mark as wrong