从我的 Typescript 代码中,我调用了一个用 C# 编写的网络服务。我的 typescript 代码看起来像这样,当我的服务返回 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>
最佳答案
您需要捕获
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
})
}
}
关于javascript - 当服务返回 Http 400 时,使用 .map 的 Http Post 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45783735/