Observable.of和Observable.from参数格式之间的唯一区别是什么?喜欢Function.prototype.call和Function.prototype.apply?
Observable.of(1,2,3).subscribe(() => {})
Observable.from([1,2,3]).subscribe(() => {})
Run Code Online (Sandbox Code Playgroud)
Tsv*_*ski 154
重要的是要注意传递类似数组的结构(包括字符串)之间of和之间的区别from:
Observable.of([1, 2, 3]).subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)
会立刻打印整个阵列.
另一方面,
Observable.from([1, 2, 3]).subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)
逐个打印元素.
对于字符串,行为是相同的,但在字符级别.
Mab*_*abd 20
一行区别:
let fruits = ['orange','apple','banana']
Run Code Online (Sandbox Code Playgroud)
from:从数组中一项一项地发出项目。例如
from(fruits).subscribe(console.log) // 'orange','apple','banana'
Run Code Online (Sandbox Code Playgroud)
of:一次发射整个数组。例如
of(fruits).subscribe(console.log) // ['orange','apple','banana']
Run Code Online (Sandbox Code Playgroud)
注意: of 运算符可以像from运算符和扩展运算符一样工作
of(...fruits).subscribe(console.log) // 'orange','apple','banana'
Run Code Online (Sandbox Code Playgroud)
Jos*_*osf 13
另一个有趣的事实是Observable.of([])在订阅它时将是一个空数组.当您订阅Observable.from([])时,您将无法获得任何价值.
使用switchmap连续保存时,这很重要.例如:
.do((data) => {
this.jobService.save$.next(this.job.id);
})
.switchMap(() => this.jobService.addSites(this.job.id, this.sites)
.flatMap((data) => {
if (data.length > 0) {
// get observables for saving
return Observable.forkJoin(jobSiteObservables);
} else {
**return Observable.of([]);**
}
})).do((result) => {
// ..
})
.switchMap(() => this.saveComments())
....
Run Code Online (Sandbox Code Playgroud)
如果addSite部分中的data.length = 0,则上面的代码返回Observable.of([]),然后去保存注释.但是如果用Observable.from([])替换它,则不会调用后续方法.
from: 从数组、promise 或 iterable 创建 observable。只取一个值。对于数组、可迭代对象和字符串,所有包含的值都将作为序列发出
const values = [1, 2, 3];
from(values); // 1 ... 2 ... 3
Run Code Online (Sandbox Code Playgroud)
of: 创建具有可变数量值的可观察对象,按顺序发出值,但数组作为单个值
const values = [1, 2, 3];
of(values, 'hi', 4, 5); // [1, 2, 3] ... 'hi' ... 4 ... 5
Run Code Online (Sandbox Code Playgroud)
https://stackblitz.com/edit/typescript-sckwsw?file=index.ts&devtoolsheight=100
| 归档时间: |
|
| 查看次数: |
35428 次 |
| 最近记录: |