【问题标题】:Why does finally() not work after catching on an Observable in Angular 2?为什么 finally() 在 Angular 2 中捕捉到 Observable 后不起作用?
【发布时间】:2018-12-14 06:26:36
【问题描述】:

我正在尝试为以 Angular 2 结尾的每个请求添加一个加载微调器,因此我扩展了 Http 服务,将其称为 HttpService。在每次请求之后,我想在捕获错误后调用 finally() 函数,以便我可以停止加载微调器。

但是打字稿说:

[ts]“Observable”类型上不存在“finally”属性。

import { AuthService } from './../../auth/auth.service';
import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions, RequestOptionsArgs, Request, Response, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class HttpService extends Http {

    constructor(
        backend: XHRBackend,
        options: RequestOptions,
        private authservice: AuthService
    ) {
        super(backend, options);
        this.updateHeaders(options.headers);
    }

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
        return super.request(url, options)
            .catch((response: Response) => this.authError(response))
            .finally(() => {
                // ...
                /* Do something here when request is done. For example
                finish a spinning loader. */
            });
    }

    private authError(response: Response) {
        if (response.status === 401 || response.status === 403) {
            this.authservice.logout();
        }
        return Observable.throw(response);
    }

    private updateHeaders(headers: Headers) {
        headers.set('Content-Type', 'application/json');
        if (this.authservice.isloggedIn()) {
            headers.set('Authorization', `Bearer ${this.authservice.getToken()}`);
        }        
    }
}

如何在每次这样的 http 请求后运行一些代码?最好的方法是什么?

【问题讨论】:

  • 我试图让 finalize() 回调工作,以便在我的应用程序中捕获取消的调用,但发现 finalize 适用于 4.3 及更高版本的 angular。对于较低版本,finally() 可以像上面的 OP 中一样使用。

标签: angular


【解决方案1】:

你忘了导入它:

import 'rxjs/add/operator/finally';

【讨论】:

  • 谢谢。我收到错误“最终不是函数”,添加此导入解决了我的问题。
  • 为我工作!
  • 那是我的问题。谢谢;)
  • 请注意,从 Angular 6 开始,引入了 rxjs 6.0 版,我们现在使用 finalize 而不是 finally,它现在在管道中使用,所以 observable.finally( x =&gt; console.log(x)).subscribe() 现在是 observable().pipe( finalize( x =&gt; console.log(x))).subscribe() 并且你导入它来自rxjs/operators 所以它将是import { finalize } from 'rxjs/operators'
  • 嘿@Stavm 你能把这个添加为答案吗?真的很有用谢谢
【解决方案2】:

注意,未来的读者:

从 Angular 6 开始,引入了 rxjs 6.0 版, 我们现在使用 finalize 而不是 finally

它现在在管道中使用,所以

observable.finally( x =&gt; console.log(x)).subscribe()

现在是

observable().pipe( finalize( x =&gt; console.log(x))).subscribe()

然后你从rxjs/operators 导入它

import { finalize } from 'rxjs/operators'

【讨论】:

  • 为我工作如下:this.http.post('logout', {}).pipe(finalize(() => { this.app.authenticated = false; this.router.navigateByUrl ('/login'); })).subscribe();谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
  • 2020-01-23
  • 1970-01-01
相关资源
最近更新 更多