Angular 2 中 Observable.prototype.subscribe 的完整回调

Mar*_*bis 8 javascript rxjs angularjs rxjs5 angular

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

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

在此处输入图片说明

例子:

成功时:

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

出错时:

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

Mar*_*idt 8

用来:rxjs 6pipe/finalize

import { finalize } from 'rxjs/operators';

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


Sea*_*kin 6

我认为你正在寻找的是.finally功能。

在源可观察序列正常或异常终止后调用指定的操作。对于浏览器< IE9 有一个名为finallyAction 的别名

这是一个例子:finally.md