2016-11-07 21 views
5

मैं एक समारोह है कि एक Observable<any> रिटर्न बनाना चाहते हैं लेकिन उसके परिणाम Observable को पास करने की एक मूल्य के क्रम में एक और asyncronous कार्य लौटने को पूरा करना होगा (एक Observable<string>), इससे पहले।कोणीय 2 rxjs नेस्ट observables

@Injectable() 
export class MyComponent 
{ 

     GetAuthToken = function() : Observable<string> 
     { 
      return this._storageService.GetAsString('authToken'); 
     } 

     GetData = function(authToken) : Observable<any> 
     { 

      let headers = new Headers(); 
      headers.append('authToken', authToken); 
      var getUsers = this._http.get('/api/endpoint', { headers: headers }) 
       .map((resonse: Response) => resonse.json())); 

      return getUsers;   
     } 


     DoIt = function() : Observable<any> 
     { 
      this.GetAuthToken().Subsribe(t=> { 
       return GetData(t); 
      }) 
     }   


} 

तो GetData समारोह में authToken पैरामीटर गुजर के बजाय, मैं GetData समारोह के भीतर GetAuthToken समारोह निष्पादित करने के लिए चाहते हैं, तो इसके पूरा होने के लिए प्रतीक्षा करें, और उसके बाद अभी भी http नमूदार लौट आते हैं।

छदाम समारोह निष्पादित ग्राहक, नहीं GetData प्रत्यक्ष वापसी होगी

+2

पूरी तरह से असंबंधित सवाल का उपयोग कर के लिए संभव है: क्यों कर रहे हैं आप सिंटैक्स का उपयोग कर रहे हैं: 'GetAuthToken = function() {...}' और 'GetAuthToken() {...} 'अन्य सभी की तरह नहीं (मुझे इन दो विधि परिभाषाओं को पता है हालांकि वही नहीं है)? – martin

+1

'Observable.forkJoin' का उपयोग करें, इसे जांचें: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/forkjoin.md –

+0

@Martin http://stackoverflow.com/प्रश्न/33685 9/जावास्क्रिप्ट-फ़ंक्शन-घोषणा-वाक्यविन-var-fn-function-vs-function-fn – gunwin

उत्तर

6

concatMap() उपयोग करके देखें:

DoIt() : Observable<any> 
{ 
    return this.GetAuthToken() 
     .concatMap(token => this.GetData(token)); 
} 
+0

बिल्कुल सही। यह काम। मेरी वेबएपीआई सेवा नहीं चल रही थी, जिससे मेरी शून्य समस्या आई। धन्यवाद! – gunwin

+0

इसी तरह की समस्या - concatMap() सही काम करता है! धन्यवाद। – Reinhard

0

यह भी flatMap

DoIt() : Observable<any> 
{ 
    return this.GetAuthToken() 
     .flatMap(token => this.GetData(token)); 
} 
संबंधित मुद्दे