RxJs:如何 "listen" 在接收流时更改订阅?
RxJs: How to "listen" to change on a subscription when it receives a stream?
我是 Angular 2 和 Observables 的新手,但我还没有找到 "listen" 在接收流时更改订阅的方法,我什至不知道如果这是可能的,或者这是正确的方法。
这是我过去对承诺所做的事情:
// Constructor and more code
// ...
ngOnInit(): void {
this.loading.present();
this.getItems()
.then(() => this.loading.dismiss());
}
getItems(): Promise {
return this.itemService
.getItems()
.then(items => this.items = items);
}
refresh(refresher): void {
this.getItems()
.then(() => refresher.complete());
}
我已经用 subscription/observables 试过了,但我不知道怎么做:
// Constructor and more code
// ...
ngOnInit(): void {
this.loading.present();
this.getItems()
.subscribe(() => this.loading.dismiss());
}
getItems(): Subscription {
return this.itemService
.getItems()
.subscribe(items => this.items = items);
}
refresh(refresher): void {
this.getItems()
.subscribe(() => refresher.complete());
}
当然,我得到一个编译错误:Property 'subscribe' does not exist on type 'Subscription'
,关于如何使用 Observables (RxJS) 实现这个的任何帮助?
一个Subscription
是听者,你总不能听听者吧?
相反,您需要 return 一个 Observable
才能订阅。将您的功能更改为如下(未测试):
getItems(): Observable<any> {
let obs = this.itemService.getItems().share();
obs.subscribe(items => this.items = items);
return obs;
}
我是 Angular 2 和 Observables 的新手,但我还没有找到 "listen" 在接收流时更改订阅的方法,我什至不知道如果这是可能的,或者这是正确的方法。
这是我过去对承诺所做的事情:
// Constructor and more code
// ...
ngOnInit(): void {
this.loading.present();
this.getItems()
.then(() => this.loading.dismiss());
}
getItems(): Promise {
return this.itemService
.getItems()
.then(items => this.items = items);
}
refresh(refresher): void {
this.getItems()
.then(() => refresher.complete());
}
我已经用 subscription/observables 试过了,但我不知道怎么做:
// Constructor and more code
// ...
ngOnInit(): void {
this.loading.present();
this.getItems()
.subscribe(() => this.loading.dismiss());
}
getItems(): Subscription {
return this.itemService
.getItems()
.subscribe(items => this.items = items);
}
refresh(refresher): void {
this.getItems()
.subscribe(() => refresher.complete());
}
当然,我得到一个编译错误:Property 'subscribe' does not exist on type 'Subscription'
,关于如何使用 Observables (RxJS) 实现这个的任何帮助?
一个Subscription
是听者,你总不能听听者吧?
相反,您需要 return 一个 Observable
才能订阅。将您的功能更改为如下(未测试):
getItems(): Observable<any> {
let obs = this.itemService.getItems().share();
obs.subscribe(items => this.items = items);
return obs;
}