Lux*_*lem 2 httpclient rxjs typescript angular
我很难掌握 http Observables 的工作方式。
Http get 总是完成,当只有一个值到达但无法查找实现时。它们是否总是在错误或值到达后完成?
我和我的同事讨论了很多,因为在每个http操作中使用以下程序:
const sub = this.http.get( enviroment.baseUrl + '/users').pipe(take(1))
.subscribe( value => {
//do something with the value
},
error => consol.log(error.message));
Run Code Online (Sandbox Code Playgroud)
后来这个:
ngOndestroy():void{
sub.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,pipe(take(1))不需要,因为 http 调用总是发出一个值。
响应或错误。
并且由于 observable 以一个值完成,因此不需要取消订阅。
如果我穿了,请纠正我。如果你有一些想法,我也很高兴能有官方消息来源。
非常感谢您提前
您可以在此处阅读源代码:
HttpClient: https://github.com/angular/angular/blob/master/packages/common/http/src/client.ts
HttpXhrBackend: https://github.com/angular/angular/blob/master/packages/common/http/src/xhr.ts
简单来说,所有 HTTP 请求的模式HttpClient如下所示:
of(request).pipe(
concactMap(request => this.xhr.handle(request))
);
Run Code Online (Sandbox Code Playgroud)
哪里request是 HTTP 请求的抽象,this.xhr是围绕 javascript XHR 的包装器 - 由HttpXhrBackend.
of(request) 返回一个自我完成的 observable,所以没有什么可担心的。
HttpXhrBackend.handle()使用本机 XHR 方法执行请求。源代码中的关键代码行是:
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();
} else {
// An unsuccessful request is delivered on the error channel.
observer.error(new HttpErrorResponse({
// The error in this case is the response body (error from the server).
error: body,
headers,
status,
statusText,
url: url || undefined,
}));
}
Run Code Online (Sandbox Code Playgroud)
我们可以在这里看到 observable 要么完成要么出错——这两种方式 observable 可以决定自己的命运。
每个人都说不需要取消订阅 http 请求的一切都是真实的 - 您可以安全地订阅并忘记。
请求通过HttpClient只会收到一个结果是不正确的,因为除了响应之外,您还可以观察其他事件。
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |