2017-08-08 17 views
1

我需要調用兩個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什麼時候?

回答

1

這是因爲傳遞給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 
) 

// ...