AngularJS

Angular – Http Get API Code Example with Promise

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:

  • Promise used with Angular Http Service (Http Get API)
  • Sample interview questions
  • Practice Test

Promise used with Angular Http Service (Get API)

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:

  • Http service is injected in the constructor. Http is part of @angular/http library.
  • Get API is invoked on Http service.
  • The http service get method returns an Observable object.
  • On an Observable object, RxJS toPromise() method is called which converts the observable to Promise object.
  • On the Promise object, the method then is invoked which returns the Promise<Rx[]>.

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);
      });
  }
}

Sample Interview Questions

  • How to use Promise with Http service in Angular App?
  • Does Angular Http get API returns a promise object?
  • How is a returned promise object processed? Show with code example.

Practice Test

[wp_quiz id=”6385″]

Further Reading

Summary

In this post, you learnt about some of the following:

  • How is Promise concept used with Angular Http service (Get API)
  • Sample interview questions
  • Practice tests to check your knowledge

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.

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

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

Share
Published by
Ajitesh Kumar

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

1 month ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

2 months ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

2 months ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

2 months ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

2 months ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

2 months ago