在 Angular 2 中 Observable.prototype.subscribe 完成回调

Complete callback in Observable.prototype.subscribe in Angular 2

完整的回调没有按预期工作。让我解释一下:

看到这张图,注意subscribe方法中的complete回调。 此 complete 函数仅在调用 observerOrNext 时调用。当发生某些错误时,不会调用 complete。这是对的?还有另一种方法来获取在进程完成时总是调用的回调?

示例:

成功时:

this.getData(params)
    .subscribe(
        successData => {
            // this is called
        },
        error => {
            // this is not called. Ok!
        },
        () => { // when complete
            // this is called, ok!
        }
    );

报错时:

this.getData(params)
    .subscribe(
        successData => {
            // this is not called, ok!
        },
        error => {
            // this is called. Ok! Yeah!
        },
        () => { // when complete
            // this is not called, why god??
        }
    );

我认为您要查找的是 .finally 函数。

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. There is an alias called finallyAction for browsers < IE9

这是一个例子:finally.md

对于 rxjs 6 使用 pipe/finalize:

import { finalize } from 'rxjs/operators';

this.getData(params)
  .pipe(
    finalize(() => {
      // this is called on both success and error
    })
  )
  .subscribe(
    (successData) => {  },
    (err) => {  }
  );