从我的Typescript代码中,我调用用C#编写的Web服务。我的打字稿代码如下所示,当我的服务返回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;
            })


javascript - 服务返回Http 400时使用.map的Http Post不起作用-LMLPHP

查看Response类的定义,它定义了诸如status, statusText之类的属性。鉴于我对Angular和Typescript的了解有限,我将假设无论从服务返回的Http代码如何,它都会在map函数内部中断?我该如何处理?我的函数返回一个Observable<boolean>

最佳答案

您需要catch可观察的错误,这是一个示例:



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

07-24 09:50
查看更多