在angular2中使用subscribe调用成功,错误回调?

Run*_*ali 11 angular2-template angular2-services angular

给responsece.json()提供的功能不适用于我的情况

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")
});
Run Code Online (Sandbox Code Playgroud)

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);
  }
Run Code Online (Sandbox Code Playgroud)

给[object,objet]如果我把地图功能服务像.map(response => response.json())给出错误就像responce.json()不是函数

请帮我

Ros*_*sco 18

尝试使用此结构:

this.AuthService.loginAuth(this.data).subscribe(
        suc => {
            console.log(suc);
        },
        err => {
            console.log(err );
        }
    );
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望将发送到服务器的数据进行字符串化,例如:

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())
}
Run Code Online (Sandbox Code Playgroud)

并且您必须在引用Http的服务的构造函数中声明一个变量,如下所示:

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

这是它对我有用的方式