Angular RxJS5-组合测试不访问角度';s的本地属性
我需要调用两个http服务和一个套接字。第一个http调用是获取元数据并在本地设置其中一个值。然后,我需要调用第二个http服务,该服务返回初始值,这些值随后通过套接字更新 这就是我到目前为止所做的:Angular RxJS5-组合测试不访问角度';s的本地属性,angular,rxjs5,Angular,Rxjs5,我需要调用两个http服务和一个套接字。第一个http调用是获取元数据并在本地设置其中一个值。然后,我需要调用第二个http服务,该服务返回初始值,这些值随后通过套接字更新 这就是我到目前为止所做的: export class MyComponent implements OnInit { subscription: Subscription; title: string; prop1: number; prop2: number; constructo
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
})
}
我相信我很接近,但似乎combinelateest
操作符没有访问本地变量,因为prop2
是未定义的。这是因为我在do
操作符中执行副作用
,而combinelatetest
没有及时看到prop2吗
注意:如果要使用开关映射
,则prop2可以工作,如下所示:
.switchMap(data => this.http.get('initialData', { prop1: this.prop1, prop2: this.prop2 }))
为什么在使用combineLatest
时prop2未定义?这是因为传递给combineLatest
的参数在调用combinelateest
之前进行计算,因此在do
收到下一个通知之前,等等
您可以使用来解决此问题:
从'rxjs/Observable'导入{Observable};
导入“rxjs/add/observable/defer”;
// ...
.联合测试(
Observable.defer(()=>this.http.get('initialData',{prop1:this.prop1,prop2:this.prop2})),
Observable.defer(()=>this.socket.get('updateEvents',{prop1:this.prop1,prop2:this.prop2})),
这是更新列表
)
// ...