Monday, November 27, 2017

Http calls in Angular with simple examples.

Angular 4Http

In this article we will be discussing about how to do an http calls in angular 2+. We already know about http calls in Angular js 1. It is entirely different in Angular 2, let us check those with very simple example. I will be using Observable concept for this.

Http get with Observable concept


Let us create a simple component first, and we need to import/inject required things.

Component


import { Component} from '@angular/core';
import {userDataService} from './userDataService';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  
  constructor(private userService:userDataService) {}
  
  triggerGetApi()
  {
    this.userService.getUserslist().subscribe(
      response => this.handleResponse(response), 
      error => this.handleError(error) 
    )
  }
  handleResponse(response:any)
  {
    console.log(response);
  }
  handleError(error:string){
    console.log(error);
  }
}

Here userDataService is nothing but our service file, where we will be making our http calls. handleResponse method will be receiving success response from http results and error in handleError method. Now let me share our userDataService file.

Service file


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    getUserslist(): Observable<any[]> {
        this._url = 'your api';

        return this.http.get(this._url)
            .map(this.handleData)
            .catch(this.handleError);
    }
    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

And we are done. I think above code is self-explanatory. Don’t forget to import/inject above mentioned dependencies. You can test this by replacing the url with your ones. You can also get many sample API for testing. I will share the module code as well for better understanding.

Module


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import {userDataService} from './userDataService';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [userDataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Http POST with Observable concept


Let us check how we can do a post call using Angular. It is almost same except we need to pass the data. Check below component code first

Component


import { Component } from '@angular/core';
import { userDataService } from './userDataService';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  item: {};
  constructor(private userService: userDataService) { }

  triggerPostApi() {
    this.item = {
      name: 'Angular',
      type: 'Framework',
      parent: 'Javascript'
    }
    this.userService.sendUserData(this.item).subscribe(
      response => this.handleResponse(response),
      error => this.handleError(error)
    )
  }
  handleResponse(response: any) {
    console.log(response);
  }
  handleError(error: string) {
    console.log(error);
  }
}

There is no difference here except we need to pass the data. Now let us check the service file code.

Service file


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    sendUserData(item: {}): Observable<{}> {

        this._url = 'your api';

        return this.http.post(this._url, item)
            .map(this.handleData)
            .catch(this.handleError);
    }

    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

We are done. If you want to pass headers also along with this add below code as well.


import { Headers, RequestOptions } from '@angular/http';
//add headers and request options


sendUserData(item: {}): Observable<{}> {

 this._url = 'your api';

 let headers = new Headers({ 'Content-Type': 'application/json' });
 let options = new RequestOptions({ headers: headers });

 return this.http.post(this._url, item, options)
  .map(this.handleData)
  .catch(this.handleError);
}

Don’t forget to add the dependencies mentioned above.

In the error block we have passed a hardcoded string in the above example. You can pass entire error block or particular message from api as well.


return Observable.throw(error.message | error);

Http Delete with Observable concept


It is almost similar to post method, check below component and service file code.

Component


import { Component } from '@angular/core';
import { userDataService } from './userDataService';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  id: Number;
  constructor(private userService: userDataService) {}
  
  triggerDeleteApi() {
    this.id = 12;
    this.userService.deleteUser(this.id).subscribe(
      response => this.handleResponse(response),
      error => this.handleError(error)
    )
  }
  handleResponse(response: any) {
    console.log(response);
  }
  handleError(error: string) {
    console.log(error);
  }

}

Service file


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    deleteUser(id: Number): Observable<Number> {
        this._url = 'your api' + id;

        return this.http.delete(this._url)
            .map(this.handleData)
            .catch(this.handleError);
    }

    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

Retry if API is failed.


This is one of the good feature in Angular 2+ (using RxJS). It will reinitiate the API call if it is failed. You can simply specify how many times this need to check. Suppose you mentioned Retry(2), it will try to call two times if API failed.

Retry()


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    getUserslist(): Observable<any[]> {
        
        this._url = 'your api';

        return this.http.get(this._url)
            .retry(2)//it will retry for two times if API failed
            .map(this.handleData)
            .catch(this.handleError);
    }
 private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
} 

Angular 4Http

Related Info

1. How to show a date is today or yesterday or last week etc using pipe - Angular

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

No comments :

Post a Comment