[英]How to resubscribe to an observable?
I have a child component view in my angular2 appplication: 我的angular2应用程序中有一个子组件视图:
.ts .TS
ngAfterViewInit() {
this.form1Observable = form1.myForm.valueChanges;
this.form1Observable.subscribe(() => // some code);
}
.html html的
<select (change)="change($event) #select>
<option value="0">New</option>
<option value="1">Existing</option>
</select>
<div *ngIf="select.value == 0">
<myForm1></myForm1>
</div>
<div *ngIf="select.value == 1">
<myOtherForm></myOtherForm>
</div>
If i change the select, i loose
the subscription that i made on the ngAfterViewInit
method, so i bind the change
method in the select to subscribe again: 如果我改变了选择,我
loose
的是我在做出认购ngAfterViewInit
方法,所以我绑定的change
在选择方法再次订阅:
change($event) {
setTimeout(() => {
if($event.target.value == 0) {
this.form1Observable.subscribe(() => // some code);
}, 500)}
//If not set this time out got an error sayng that form1 is undefined.
The problem is that when i execute this change($event)
method, the subscription doesnt work. 问题是,当我执行此
change($event)
方法时,订阅不起作用。 Why? 为什么?
I would recommend just setting up the subscribe
directly on the myForm.valueChanges
and having it store a variable on the component. 我建议只在
myForm.valueChanges
上直接设置subscribe
,并将其存储在组件上。 Then you can execute code on the variable instead of resubscribing. 然后,您可以对变量执行代码,而无需重新订阅。 Copying
valueChanges
into a new variable won't get the updates sent to valueChanges
. 将
valueChanges
复制到新变量中不会将更新发送到valueChanges
。
If you wanted to create a new Observable from the valueChanges
Observable, you could wrap its output in a ReplaySubject or BehaviorSubject method: 如果要从
valueChanges
Observable创建一个新的Observable,可以将其输出包装在ReplaySubject或BehaviorSubject方法中:
ngAfterViewInit() {
this.form1Observable = new ReplaySubject<any>();
form1.myForm.valueChanges.subscribe((thing) => this.form1Observable.next(thing));
this.form1Observable.subscribe(() => // some code)
}
This seems counter-intuitive however, I'm sure depending on your use of the observable output that there's a better way for you to do this. 但是,这似乎违反直觉,我敢肯定,根据您对可观察到的输出的使用,有更好的方法来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.