【问题标题】:Observable closed on errorObservable 因错误而关闭
【发布时间】:2016-12-26 20:07:20
【问题描述】:

我对 Angular 2 中的 Observable 有疑问。

我将我的组件订阅到一个 observable,然后当我的服务具有新值时,我的组件会收到通知。
问题是当观察者推送错误时,比如 HTTP 错误,我的 observable 已关闭,因此我的组件不再收到通知。

问题
即使出现错误,如何让我的组件继续侦听我的服务?

示例
这里是example

这是我的代码:

组件

constructor(private appService: AppService) {
    //I subscribe my component to an observable
    this.appService.commentsObservable.subscribe((comments) => {
        console.log(comments);
    }, (err) => {
        console.log(err);
    });
}

getComments() {
    //I ask the service to pull some comments
    this.appService.getComments()
}

服务

private commentsObserver: Observer<any>;
commentsObservable: Observable<any>;

constructor() {
    this.commentsObservable = new Observable((observer) => {
        this.commentsObserver = observer;
    });
}

getComments() {
    setTimeout(() => {
        //You will see the result displayed by the component
        this.commentsObserver.next([]);
    }, 0);

    setTimeout(() => {
        //You will see the result displayed by the component
        this.commentsObserver.next([]);
    }, 500);

    setTimeout(() => {
        //You will see the error displayed by the component
        this.commentsObserver.error({_body: 'Nice errroorr'});
    }, 1000);

    setTimeout(() => {
        //You won't see this one, why ?
        this.commentsObserver.next([]); 
    }, 1500);
}

【问题讨论】:

    标签: angular rxjs observer-pattern


    【解决方案1】:

    这是预期的行为。 According to the documentation,

    在 Observable Execution 中,可能会传递零到无限的 Next 通知。如果发送了错误或完成通知,则之后无法发送任何其他通知。

    对于上面的代码,可能是

    this.appService
    // error is caught, but the observable is completed anyway
    .catch((err) => {
        console.error(err)
        return Observable.empty();
    })
    // re-subscribe to completed observable
    .repeat()
    .subscribe((comments) => console.log(comments));
    

    但是考虑到预期的行为,使用 RxJS 错误处理来提供具有非关键错误值的连续 observable 是不切实际的。相反,它可能会更改为

    setTimeout(() => {
        //You will see the error displayed by the component
        this.commentsObserver.next(new Error('Nice errroorr'));
    }, 1000);
    

    this.appService.commentsObservable.subscribe((comments) => {
        if (comments instanceof Error)
            console.error(comments);
        else
            console.log(comments);
    });
    

    方法可能因实际情况而异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-04
      • 2013-11-15
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多