2025-01-30 05:00:11

'操作符'中的' vs '

是可观察对象之间唯一的区别。和Observable.from arguments format?比如Function.prototype.call和Function.prototype.apply?

Observable.of(1,2,3).subscribe(() => {})
Observable.from([1,2,3]).subscribe(() => {})

当前回答

from操作符获取事件源。从(源)

let array = [1,2,3,4,5]
from(array); //where array is source of events, array[of events]


let promise = new Promise(function(resolve, reject) {
  // executor (the producing code, "singer")
});
from(promise); //where promise is source of event, promise(of event)





let observable = Observable.create(function(observer) {
  observer.next(1);
  observer.next(2);
  observer.next(3);
  observer.next(4);
  observer.next(5);
  observer.complete();
});
from(observable); // where obsservable is source of events. 

运算符of接受单个事件。(event1, event2, event3)

of(1,2,3,4,5); // where 1,2,3,4,5 are individual events

其他回答

from操作符获取事件源。从(源)

let array = [1,2,3,4,5]
from(array); //where array is source of events, array[of events]


let promise = new Promise(function(resolve, reject) {
  // executor (the producing code, "singer")
});
from(promise); //where promise is source of event, promise(of event)





let observable = Observable.create(function(observer) {
  observer.next(1);
  observer.next(2);
  observer.next(3);
  observer.next(4);
  observer.next(5);
  observer.complete();
});
from(observable); // where obsservable is source of events. 

运算符of接受单个事件。(event1, event2, event3)

of(1,2,3,4,5); // where 1,2,3,4,5 are individual events

一行区别:

       let fruits = ['orange','apple','banana']

from:从数组中逐个生成项。例如

    from(fruits).subscribe(console.log) // 'orange','apple','banana'

of:一次性释放整个数组。例如

 of(fruits).subscribe(console.log) //  ['orange','apple','banana']

注:of运算符可以表现为from运算符与展开运算符

 of(...fruits).subscribe(console.log) //  'orange','apple','banana'

的值会同时发出所有的值

From将逐一发出所有值

with展开运算符= from运算符

在传递一个类数组结构(包括字符串)时,注意of和from之间的区别是很重要的:

Observable.of([1, 2, 3]).subscribe(x => console.log(x));

会立刻打印出整个数组。

另一方面,

Observable.from([1, 2, 3]).subscribe(x => console.log(x));

逐个打印元素。

对于字符串,行为是相同的,但在字符级别。

当我想到与.call / .apply方法的类比时,我发现更容易记住它们的区别。

你可以这样想:

通常,单独传递的所有参数(用逗号分隔)也会按照传递的顺序单独发出。Of()只是逐个发出所有参数(就像.call方法将参数传递给被调用的函数一样) 从某种意义上说,From()类似于.apply,它可以接受一个值数组作为参数,并将数组元素转换为用逗号分隔的独立参数。

因此,如果您有一个数组,并希望每个元素分别发出,您可以使用from()或通过使用of()和扩展操作符(如of(…arr))来获得相同的行为。

这有点复杂(从也可以观察到),但通过这个类比,可能会更容易记住主要的区别。