Figure 1. In Javascript, promise are resolved or rejected
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”.
Figure 1. In Javascript, promises are either resolved or rejected
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.
Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…
Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…
Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…
Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…
The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…
Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…
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