我目前正在扩展我对 RxJ 的了解,并试图更好地理解流。 我想将 Http 响应与 of() 生成的 Observable 进行比较。
我们可以说 JSON 响应与元素“a”进行比较时被视为元素“a”吗?
of(['a', 'b', 'c'])
?
当我们得到 JSON 响应时,它总是像只得到一个元素?
http 响应是 Observable 流中的一个元素吗?
编辑: 显然,我应该将它与 Interval() 的第一个发出值进行比较。
最佳答案
使用 Angular HTTP 客户端的 HTTP 请求实际上是 HttpRequest
类型的 RxJS observable产生 HttpEvent
类型的通知流。如果您希望查看所有通知,请在请求中使用选项observe: 'events'
。如果未提供此选项(默认),则仅返回最后一个通知(HTTP 请求的结果),如 here 所示。 .
来自docs :
When using
HttpClient.request()
with an HTTP method, configure the method withobserve: 'events'
to see all events, including the progress of transfers.
看到这一点,您的 of(['a', 'b', 'c'])
示例与 HTTP 请求并不相似,因为它只发出一个通知(数组 ['a', 'b', 'c']
) 并完成。但是 from(['a', 'b', 'c'])
与 HTTP 请求类似,因为它单独发出每个项目。
Is HTTP response one element in Observable stream?
是的,这是通知流中的最后一个通知。它的类型为 HttpEventType.Response
.
工作示例:Stackblitz
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
events = [];
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get<any>('https://jsonplaceholder.typicode.com/todos/1', {observe: 'events'}).subscribe((event: HttpEvent<any>) => {
this.events.push(event);
console.log(event);
});
}
}
type: 0
对应于 HttpEventType.Sent
,type: 4
对应于 HttpEventType.Response
。您可能会在更复杂的请求(例如视频上传请求)中看到更多事件。
关于angular - http 响应是 Observable (Rxjs) 流中的一个元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62434563/