RxJS5 - combineLatest无法访问Angular的本地属性
问题描述:
我需要调用两个http服务和一个套接字。第一个http调用是获取元数据并在本地设置其中一个值。然后,我需要调用第二个http服务,它返回通过套接字更新后的初始值。RxJS5 - combineLatest无法访问Angular的本地属性
这是我到目前为止有:
export class MyComponent implements OnInit {
subscription: Subscription;
title: string;
prop1: number;
prop2: number;
constructor(private http: HttpService,
private socket: SocketService,
private route: ActivatedRoute) {
}
ngOnInit() {
this.prop1 = this.route.snapshot.parent.params['prop1'];
this.subscription = this.http.get('/metaData')
.do(data => {
this.title = data.title;
this.prop2 = data.prop2;
})
//this.prop2 is undefined in combineLatest...
.combineLatest(
this.http.get('initialData', { prop1: this.prop1, prop2: this.prop2 }),
this.socket.get('updateEvents', { prop1: this.prop1, prop2: this.prop2 }),
this.updateList)
.subscribe(data => {
this.data = data
})
}
我相信我靠近,但现在看来,该combineLatest
手术者没有访问本地变量作为prop2
是undefined
。这是因为我在do
运营商中做side effect
,prop2是否被combineLatest
准时看到?
注:如果我使用switchMap
,PROP2的作品,像这样:
.switchMap(data => this.http.get('initialData', { prop1: this.prop1, prop2: this.prop2 }))
为什么PROP2 undefined
使用combineLatest
什么时候?
答
这是因为传递给combineLatest
参数被combineLatest
之前计算被称为 - 和,因此,do
接收下通知之前,等
您可以使用defer
来解决这个问题:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/defer';
// ...
.combineLatest(
Observable.defer(() => this.http.get('initialData', { prop1: this.prop1, prop2: this.prop2 })),
Observable.defer(() => this.socket.get('updateEvents', { prop1: this.prop1, prop2: this.prop2 })),
this.updateList
)
// ...