2016-12-26 83 views
4

我有角2可觀察封閉錯誤

與可觀察到的問題,我訂閱我的組件,以可觀察到的,那麼當我的服務有新的價值,我的組件被通知。
問題是當觀察者推送一個錯誤,就像一個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); 
} 

回答

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錯誤處理以提供一個連續的可觀察到的與非關鍵錯誤值。相反,它可能會更改爲

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

該方法可根據實際情況而有所不同。