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

角度http:头404 http响应

  •  1
  • Jordi  · 技术社区  · 6 年前

    我已经编写了此http调用方法:

    public exists(id: string): Observable<boolean> {
        const buildURL = () => map((userId: string) => this.buildIdURL(userId));
        const buildResponse = () => map(() => true);
        const onErrorGetDetails = <T>() => catchError<T, boolean>((error: Response) => this.handleError(error));
        const makeRequest = () => switchMap((url: string) => this.authHttp.head(url));
    
        return Observable.of(id)
            .pipe(
                buildURL(),
                makeRequest(),
                buildResponse(),
                onErrorGetDetails()
            );
    }
    

    所以,我试图处理以下情况:

    1. 404,我需要返回 Observable.of(false)
    2. 否则,返回 Observable.throw(error)

    有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Carbamate    6 年前

    我希望我已经明白你需要什么了。这个 error 你从 catchError 方法应包含状态代码。因此,您可以正确处理它。

    我没有进行适当的搜索,但我记得使用 HttpErrorResponse 而不是 Response 获取有关HTTP响应的更多信息。

    几个月前我写了这样的东西:

    const onErrorGetDetails = <T>() => catchError<T, boolean>((error: HttpErrorResponse) => {
        if (error.status === 404) {
            return of(false)
        }
        return throwError(error)
    
        2
  •  0
  •   Robert    6 年前

    要实现这一点,您需要设置一个名为

    {observe: 'response'} 
    

    允许您读取http调用的响应状态。 因此,http调用将是:

      makeCall(): Observable<any> {
            return this.http.get('uri', {observe: 'response'});
          } 
    

    当您要订阅时,只需检查错误状态,即使不订阅也可以检查错误状态,为此,只需使用管道和map或catchError并检查响应即可。

    下面是我如何在jwt验证中实现这一点的示例:

    return this.auth.validateJwt().pipe(
            map( (response) => {
              if (response.status === 200) {
                return true;
              }
            }),
            catchError((err: Response) => {
              this.handleError('authentication');
              if (err.status === 200) {
                return of(true);
              }
    
              return of(false);
            }),
            first()
          ); 
    

    我映射响应错误以查看代码是否为200,映射响应意味着服务器将返回一些内容,记住我们将收到完整的响应,因此响应将由标题、正文响应组成,其中正文是数据。但是如果服务器脱机或者我在代码上键入了错误的url,我会捕获错误,因为即使没有正文,我仍然有响应。

    角度文档: https://angular.io/guide/http#reading-the-full-response

    推荐文章