从我的Typescript代码中,我调用了一个用C#编写的webservice。我的打字稿代码看起来像这样,当我的服务返回HTTP200时,它按预期工作,但是当服务器拒绝凭据并抛出HTTP 400时,它不会在map函数内部中断。
return this.http.post(this.authenticationEndpoint, params)
.map((response:Response) => {
let resp = response;
let token = response.json() && response.json().access_token;
if(token){
this.token = token;
localStorage.setItem('user', JSON.stringify({userName: userName, token:token}));
return true;
}
return false;
})
查看Response
类的定义,它定义了status, statusText
等属性。鉴于我对Angular和Typescript的了解有限,我会假设无论从我的服务返回的Http代码如何,它都会在map
函数内部破坏?我该如何处理这个案子?我的函数返回Observable<boolean>
答案 0 :(得分:3)
你需要catch
这里的Observable Errors是一个例子:
export class ApiGateway {
baseURL = "https://myapi.com"; // or sometimes pulled from another file
constructor(private http: Http) {}
get(path, params) {
showLoadingIndicator();
let headers = this.createMySpecialHeaders();
let options = {
headers: headers
} // and whatever else you need to generalize
let fullUrl = this.baseUrl + path + '?' + this.urlEncode(params)
`;
return this.get(path, params, options)
.do(() => hideLoadingIndicator())
.map(res => res.json())
.catch(err => {
hideLoadingIndicator();
// show error message or whatever the app does with API errors etc
// sometimes rethrow the error, depending on the use case
})
}
}