代码之家  ›  专栏  ›  技术社区  ›  Vojtech

如何处理API服务中的HTTP错误,只有在成功的情况下才能通过可观察的方式返回响应?

  •  0
  • Vojtech  · 技术社区  · 7 年前

    在我的Angular2应用程序中,我有一个 API.服务 使用方法 发送请求 应该这样做:

    1. 向服务器发送请求
    2. 将Promise返回给调用方(我只希望调用方获得成功响应)
    3. 如果发生错误,请在本地处理错误(导航用户登录或显示弹出窗口)

    我用承诺来实现它:

    sendRequest(method: string, url: string, data: any) : Promise<any> {
        return this.http.request(method, url, {
            body: data,
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Authorization': 'bearer ' + token,
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).toPromise().catch((res) => this.handleError(res));
    }
    
    handleError(response: any) {
        if (response.status === 401 || response.status === 403) {
            this.tokenService.deleteToken();
            this.router.navigate(['login']);
        }
        // Show popup etc.
        ...
    }
    

    我想用Observable代替Promise:

    sendRequest(method: string, url: string, data: any) : Observable<any> {...}
    

    请告诉我怎么做。谢谢您。

    编辑1 :我找到处理响应的示例,然后将一些结果传递给观察者。这不是我需要的。如果发生错误,不应通知观察者。只有在收到成功的答复时,才应通知观察员。如果发生错误,应在内部处理 API.服务 只有。

    3 回复  |  直到 7 年前
        1
  •  0
  •   mittal bhatt    7 年前
    sendRequest(method: string, url: string, data: any) : Observable<any> {
        return this.http.request(method, url, {
            body: data,
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Authorization': 'bearer ' + token,
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).map((response: Response) => <any>response.json()).catch(this.handleError);
    }
    
    handleError(response: any) {
        if (response.status === 401 || response.status === 403) {
            this.tokenService.deleteToken();
            this.router.navigate(['login']);
        }
        // Show popup etc.
        ...
    }
    
    //get response like below
      this.yoursevice.sendRequest(resdata)
            .subscribe((resdata) => {}, 
    (error) => {
                this.statusMessage =
                    'Problem with the service. Please try again after sometime';
                console.error(error);
            }););
    
        2
  •  1
  •   Atul    7 年前

    请看下面-

    sendRequest(method: string, url: string, data: any) : Observable<any>{
        return this.http.request(method, url, {
            body: data,
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Authorization': 'bearer ' + token,
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).map( ( res ) => {
          return res || {};
        } )
        .catch( this.handleError );
    }
    
    
    
    handleError(response: any) {
        if (response.status === 401 || response.status === 403) {
            this.tokenService.deleteToken();
            this.router.navigate(['login']);
        }
        // Show popup etc.
        ...
    }
    
        3
  •  0
  •   bugs    7 年前

    http.request 默认情况下返回可观察的,但您正在将其转换为具有 .toPromise()

    只需将函数的签名更改为返回 Observable<any> 把你能看到的转化为承诺的部分去掉( .toPromise().catch((res) => this.handleError(res)) )。

    你还需要改变你倾听回应的方式(你很可能会 then 在调用服务方法的地方,需要将其更改为 subscribe 这基本上是对可观测数据的等效版本)。

    this answer 有关如何在使用Observable时正确捕获异常的详细说明。