sta*_*lay 7 rxjs ionic-framework ionic2 angular
我已经看过像rxjs这样的教程.
我的问题是:
1)take(1)这里的用法是什么?我在网上看到了很多解释,但我并没有真正理解.此外,我认为take(1)在此代码中使用没有任何好处.并且作者take(1)在REST api相关服务中使用每个返回函数.
2)作者在订阅后没有取消订阅.是因为作者使用take(1)因此不需要手动取消订阅?
3)如果我想实现catch功能怎么办?我应该在服用前或服用后实施.
getProfile() { // this is a call to REST API
return this.service.getProfile()
.map(res => res.json())
.take(1)
}
}
this.data.getProfile().subscribe(profile => {
this.userProfile = profile;
});
Run Code Online (Sandbox Code Playgroud)
订阅后,作者没有取消订阅.是因为作者使用take(1)因此不需要手动取消订阅?
是的,这很可能是作者使用take(1)运算符的原因.它的工作是将一个值传递给一个observable,然后取消订阅源.但根据服务,可能不需要.
例如,在Angular中,HttpClient服务在发送最终HttpResponse事件值后自行完成流,因此您既不需要take显式使用也不需要取消订阅.以下是消息来源:
@Injectable()
export class HttpXhrBackend implements HttpBackend {
...
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
...
// Everything happens on Observable subscription.
return new Observable((observer: Observer<HttpEvent<any>>) => {
...
// First up is the load event, which represents a response being fully available.
const onLoad = () => {
...
if (ok) {
// A successful response is delivered on the event stream.
observer.next(new HttpResponse({
body,
headers,
status,
statusText,
url: url || undefined,
}));
// The full body has been received and delivered, no further events
// are possible. This request is complete.
observer.complete(); <---------------------------------
}
Run Code Online (Sandbox Code Playgroud)
如果我想实现catch功能怎么办?我应该在服用前或服用后实施.
您可以在之后实现它,take因为它take也会传输错误.
const stream = Observable.create((observer) => {
observer.error(new Error());
}).take(1).catch(() => {
return Observable.of(`An error occurred`);
}).subscribe((v) => {
console.log(v); // An error occurred
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3908 次 |
| 最近记录: |