首页 > 解决方案 > 如果 Api 离线,则 Angular 状态为 0

问题描述

如果 API 在我的 Angular 应用程序上脱机,我正在尝试显示一条消息。

在我的 HttpInterceptor 中,我有:

return next.handle(request).pipe(
    tap(
        event => {
            if (event instanceof HttpResponse) {
                // console.log('all looks good');
                // http response status code
                //console.log(event.status);
            }
        },
        error => {
            if (error.status == 0) {
                error.message = 'API is Offline.', 'error'
            }
            console.error(error.status);
            console.error(error.message);
        }
    )
);

因此,当他失败时,我想拦截错误以返回我的组件或服务的消息。

我的组件调用服务:

this._service.new()
    .subscribe(
        res => {
        },
        err => {
          this._messageHelperService.showToast(err.error.message, 'error');
        }
    );

有人可以帮助我吗?谢谢。

标签: angularapihttpionic-frameworkconnection

解决方案


尝试throwError在 HttpInterceptor 中使用抛出错误。

例子:

    tap(
        event => {
            if (event instanceof HttpResponse) {
                // console.log('all looks good');
                // http response status code
                //console.log(event.status);
            }
        },
        error => {
            if (error.status === 0) {
                return throwError('API is Offline., error')
               // error.message = 'API is Offline.', 'error'
            }
            console.error(error.status);
            console.error(error.message);
        }
    )
);

然后您可以以与您使用相同的方式访问组件中的错误。


推荐阅读