angularangular2-templateangular2-services

Calling success, error callbacks using subscribe in Angular 2


It is giving responce.json () is not a function for my case.

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

File 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 use a map function service, like .map(response => response.json()), it is giving an error like responce.json () is not function.


Solution

  • 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.