【问题标题】:How do I handle a get reqest to an offline source in Angular2?如何在 Angular 2 中处理对离线源的获取请求?
【发布时间】:2025-11-25 13:20:03
【问题描述】:

我有以下问题:我有一个 Angular 2 应用程序,它发送如下获取请求:

getStatus(cb:(boolean, error) => void){
    this.http.get(this.uri+'/forms/status')
    .subscribe(
        (res: Response) =>{
            console.dir(res);
            this.response = res;
            if(res.status === 200)cb(true, null);
            else cb(false, "No connection established");
        }
    )
}

所以这个方法应该检查我的服务是否在线,如果它离线,应该向用户发送消息。我的问题是我总是会得到 ​​p>

加载资源失败:net::ERR_CONNECTION_RESET 当我调用该方法时。 我的问题是,当我的服务处于脱机状态时,该方法仅将布尔值返回为 false,我该如何处理。

最好的问候。

切换到

getStatus(cb:(boolean, error) => void){
this.http.get(this.uri+'/forms/status')
.map(val => true)
.catch(err => Observable.of([false])
.subscribe(
    (res: boolean) => cb(res, res ? null : "No connection established");)
}

返回错误信息:

ERROR in [default] C:\Development\Code\formcreator-ui\app\src\service\form.servi
ce.ts:66:8
Argument of type '(res: boolean) => void' is not assignable to parameter of type
 'NextObserver<boolean[]> | ErrorObserver<boolean[]> | CompletionObserver<boolea
n[]> | ((value: boo...'.
  Type '(res: boolean) => void' is not assignable to type '(value: boolean[]) =>
 void'.
    Types of parameters 'res' and 'value' are incompatible.
      Type 'boolean[]' is not assignable to type 'boolean'.

【问题讨论】:

    标签: rest angular http-get


    【解决方案1】:

    如果您的意思是在浏览器控制台中隐藏错误消息,那么您就不走运了。此错误是浏览器造成的,无法避免。

    否则这应该做你想要的。

    getStatus(cb:(boolean, error) => void){
        this.http.get(this.uri+'/forms/status')
        .map(val => true)
        .catch(err => Observable.of([false])
        .subscribe(
            (res: Response) => cb(res, res ? null : "No connection established");
        )
    }
    

    但不是cb 我会这样做

    getStatus(){
        return this.http.get(this.uri+'/forms/status')
        .map(val => true);
        .catch(err => Observable.of([false])
    }
    

    那么它可以像这样使用

    this.getStatus().subscribe(avail => avail ? doSomething() : console.log("No connection"));
    

    Observables 是为了避免回调地狱,因此最好使用此功能而不是传递回调。

    【讨论】:

    • 当我尝试这个时,它在 map(true) 处失败,并显示“布尔类型的参数不能分配给类型的参数(值:布尔值 [],索引:数字)”
    • 你能试试Observable.of(false)吗?我自己不使用 TS,也不完全确定所有细节。
    • 也不起作用。它适用于 mapTo(true),但我无法订阅它。
    • 愚蠢的。 map应该是.map((val) =&gt; true)catch,地图需要切换。
    • 很抱歉再次打扰您,这对我来说是一个全新的世界。似乎 subscribe 需要 NextObserver :/