Angular 可观测闭合误差

Angular 可观测闭合误差,angular,rxjs,observer-pattern,Angular,Rxjs,Observer Pattern,我对角度2的可观测性有个问题 我将我的组件订阅给一个可观察的对象,然后当我的服务有了新的价值时,我的组件就会收到通知。 问题是,当观察者推送错误(如HTTP错误)时,我的可观察对象关闭,因此我的组件不再收到通知 问题 即使我有错误,我如何使我的组件继续侦听我的服务 示例 这是一个 这是我的代码: 组件 constructor(private appService: AppService) { //I subscribe my component to an observable

我对角度2的可观测性有个问题

我将我的组件订阅给一个可观察的对象,然后当我的服务有了新的价值时,我的组件就会收到通知。
问题是,当观察者推送错误(如HTTP错误)时,我的可观察对象关闭,因此我的组件不再收到通知

问题
即使我有错误,我如何使我的组件继续侦听我的服务

示例
这是一个

这是我的代码:

组件

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);
}
私有服务器:观察者;
可评论的:可观察的;
构造函数(){
this.commentsObservable=新的可观察对象((观察者)=>{
this.commentsObserver=观察者;
});
}
getComments(){
设置超时(()=>{
//您将看到组件显示的结果
this.commentsObserver.next([]);
}, 0);
设置超时(()=>{
//您将看到组件显示的结果
this.commentsObserver.next([]);
}, 500);
设置超时(()=>{
//您将看到组件显示的错误
this.commentsObserver.error({u body:'Nice errroorr'});
}, 1000);
设置超时(()=>{
//你看不到这个,为什么?
this.commentsObserver.next([]);
}, 1500);
}

这是预期的行为

在可观察的执行中,可能会发送零到无限的下一个通知。如果传递了错误或完整的通知,则之后不能传递任何其他内容

对于上面的代码,它可能是

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错误处理来提供具有非临界错误值的连续可观测值是不现实的。相反,它可以改为

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);
});