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手术者没有访问本地变量作为prop2undefined。这是因为我在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 
) 

// ...