在这种情况下,我对代码流有些困惑。请参考下面的代码。
import { fromEvent } from 'rxjs';
import { mapTo } from 'rxjs/operators';
let btn = document.getElementById("btnclick");
let btn_clicks = fromEvent(btn, 'click');
let positions = btn_clicks.pipe(mapTo ("Testing MapTo"));
positions.subscribe(x => console.log(x));
Testing MapTo
当我单击按钮时输出。一开始我以为只要单击按钮,就会.pipe()
调用该.subscribe()
方法,然后再调用该方法,使它在控制台中输出。但是我读过
subscribe is for activating the observable and listening for emitted values
在链接中。
问题:
this.http.get('url')
.pipe(
filter(x => x % 2 === 0),
map(x => x + x)
)
.subscribe(x => {
console.log(x);
}
当您了解的含义时,流程就会很清楚pipe
。它按照它所说的那样,在源和订阅发出的值之间传递内容。
source ---> modify results by ---> subscription
piping in operators
click ---> map (convert) click event ---> console.log(x)
event to string "Testing MapTo"
Http ---> go forward only if ---> map (convert) ---> console.log(x)
observable number is even result = 2 * result
当观察对象被订阅时(例如positions.subscribe(x...
),将subscribe
调用Observable类的方法。之后,回调函数进入中断模式,并等待观察对象发出。这是关键。订阅触发可观察到的动作语句序列,但它不知道什么时候会观察到发射。这就是为什么将可观察值称为获取值的推入方法。当可观察对象准备就绪时,将其推送。
一旦subscribe
触发了可观察类中的pipe
函数,该函数便开始发挥作用。因为请记住,可观察对象不是直接订阅的。是的someObs.pipe(...).subscribe()
。这类似于声明someData.getSum().getAverage()
。getSum()
应用于函数的结果someData
将是getAverage()
函数的输入。以相同的方式,管道中的运算符将应用于源可观察对象,该源将返回新的修改后的可观察对象。订阅将等待这个可观察到的事件。
订购披萨场景
+----------------------------------+---------------------------------------+
| Ordering pizza | Subscribing to observable |
+----------------------------------+---------------------------------------+
| Place order | Subscribe to observable |
| Kitchen worker starts processing | The observable starts processing |
| No onions | Filter some values |
| Double chesse | Map the values to return (2 * values) |
| Some other toppings | Some other operators |
| Receive the pizza | Receive the value |
+----------------------------------+---------------------------------------+
这里要注意的两个重要事项:
您订购披萨,然后等待。您不知道什么时候会收到披萨(非正式地说,一些特权人士可能会打招呼,排长队)。订阅不知道何时接收数据的方式相同。这就是使它异步的原因(幸运的是,RxJS不会基于任何事物进行区分)。所有订阅将等待,无论其属性如何。
现在很容易会误认为订阅与可观察项没有任何关系。那只是观察者在等待观察者已经开始处理其语句而等待接收数据。那是错误的。在这种情况下,订阅回调应在您订阅后立即接收数据。但是实际上,可观察对象直到被订阅后才开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句