2017-02-13 109 views
4

給予responce.json()不爲我的情況下發揮作用調用成功,在angular2中使用訂閱錯誤回調?

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

給予[對象,客體] 如果我把.map(response => response.json())這樣的map函數服務給出錯誤,像responce.json()不是函數

請幫我

回答

5

嘗試使用這種結構:

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

你也可能要字符串化你的數據被髮送到服務器,如:

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()) 
} 

而且你必須聲明在你的服務的構造函數中引用Http的變量,如下所示:

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

這是它爲我工作

1

在服務頁面

//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()}); 
}); 

的方式和你的模板TS文件

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']); 
    } 
}); 

這是完全

爲我工作
相關問題