calling success, error callbacks using subscribe in angular2?

Runali picture Runali · Feb 13, 2017 · Viewed 27.2k times · Source

Giving responce.json () is not function for my case

component.ts

 this.AuthService.loginAuth(this.data).subscribe(function(response) {
  console.log("Success Response" + response)
},
  function(error) {
  console.log("Error happened" + error)
},
  function() {
  console.log("the subscription is completed")
});

AuthService.ts

     loginAuth(data): Observable<any> {
  return this.request('POST', 'http://192.168.2.122/bapi/public/api/auth/login', data,{ headers:this. headers })
      .map(response => response)
      //...errors if any
      .catch(this.handleError);
  }

Giving [object,objet] If I put map function service like .map(response => response.json()) is giving error like responce.json () is not function

Please help me

Answer

Rossco picture Rossco · Feb 13, 2017

Try using this structure:

this.AuthService.loginAuth(this.data).subscribe(
        suc => {
            console.log(suc);
        },
        err => {
            console.log(err );
        }
    );

Also you might want to stringify your data being sent to the server such as:

loginAuth(data) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    var info = JSON.stringify(data);

    return this._http.request("http://192.168.2.122/bapi/public/api/auth/login", info , { headers: headers }).map(res => res.json())
}

And you must declare a variable in the constructor of your service referencing Http like such:

import { Http, Headers, Response, URLSearchParams } from '@angular/http';    
constructor(private _http: Http) {
}

This is the way it worked for me