Angular2: HTTP Get with multiple query string term Using Promises in Angular 2 Application

Standard

The Angular Http client communicates with the server using a familiar HTTP request/response protocol. The Http client is one of a family of services in the Angular HTTP library. When importing from the @angular/http module, SystemJS knows how to load services from the Angular HTTP library because the systemjs.config.js file maps to that module name. The HttpModule is necessary for making HTTP calls.

Promise

Although the Angular http client API returns an Observable you can turn it into a Promise. It’s easy to do, and in simple cases, a promise-based version looks much like the observable-based version:

  • You can follow the promise then(this.extractData).catch(this.handleError) pattern.
  • Alternatively, you can call toPromise(success, fail). i.e. -> .toPromise(this.extractData, this.handleError).
  • The errorHandler forwards an error message as a failed promise instead of a failed promises.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

HTTP GET using Promises with multiple query string term

See extended DEMO on Github

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } 
from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class WebApiPromiseService {
    headers: Headers;
    options: RequestOptions;

    constructor(private http: Http) {
        this.headers = new Headers({ 'Content-Type': 'application/json', 
                                     'Accept': 'q=0.8;application/json;q=0.9' });
        this.options = new RequestOptions({ headers: this.headers });
    }

    getServiceWithMultipleQueryTerm(url: string, query: string): Promise<any> {
    return this.http
        .get(url + "/?" + query, this.options)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

Usage Code:

import { Component, OnInit } from '@angular/core';

import { SearchMovieModel } from './search-movie.model';
import { WebApiPromiseService } from './web-api-promise.service';

@Component({
    selector: 'search-movie-list',
    templateUrl: '../../Scripts/app/search-list.component.html'
})

export class SearchMovieListComponent implements OnInit {
    searchMovieModel: SearchMovieModel;
    
    constructor(
        private moviePromiseService: WebApiPromiseService) {
       
        this.searchMovieModel = {id: '12' , name: 'abc'};
    }

    ngOnInit() {
        this.moviePromiseService
          .getServiceWithMultipleQueryTerm('api/Movie/TestGetParam', "id=1&&name=abc")
          .then(result => console.log(result))
          .catch(error => console.log(error));
    }
}

 

Important Note

You need to append Accept headers to your get request in order for Firefox to render the json that comes back.

In the headers object, the Content-Type specifies that the body represents JSON. The headers object is used to configure the options object. The options object is a new instance of RequestOptions, a class that allows you to specify certain settings when instantiating a request. In this way, headers is one of the RequestOptions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s