Successful, error callbacks using subscription in angular2?

Providing responce.json () is not a 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); } 

Providing [object, objet] If I put a map function function, for example .map (response => response.json ()), it threw an error, for example responce.json () does not work

Please help me

+5
source share
2 answers

Try using this structure:

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

In addition, you may need to strengthen your data sent to the server, for example:

 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 should declare a variable in the constructor of your service, referring to Http, for example:

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

Here's how it worked for me

+6
source

On the service page

 //Import if needed import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; let options = new RequestOptions({ headers: this.headers }); return this.http.post('http://192.168.2.122/bapi/public/api/auth/login', data, options) .map((res: Response) => { return { "res": res.json() }; }) .catch((e: any) => { console.log(e.status); return Observable.throw({"Errors":e.json()}); }); 

And your ts file template

 this.AuthService.loginAuth(this.data).subscribe((result: any) => { let res = result.res; console.log(res) },(error: any) => { if(typeof error['Errors'] !="undefined"){ console.log(error['Errors']); } }); 

It works great for me.

+1
source

Source: https://habr.com/ru/post/1264155/


All Articles