2017-03-02 59 views
1

我有被分配的值的服務共享組件之間的變量如下,爲什麼我不能分配和使用組件內的值?

import { Injectable } from '@angular/core'; 
import { Subject } from 'rxjs/Subject'; 

@Injectable() 
export class AppMessageQueuService {  
    checkOutPageParams: Subject<Object>; 
    constructor() {  
     this.checkOutPageParams = new Subject<string>(); 

    } 

} 

我使用這項服務於以下參數傳遞到另一組件時,

this.appMsgService.checkOutPageParams.next({ 
      'userId': listItem.userInfo.userId, 
      'listingId': listItem.listingId, 
      'event': this.event 
     }); 

我可以看到到事件當我調試,這是我如何得到在第二個組件的值,

this.appMsgService.checkOutPageParams.asObservable() 
      .switchMap((params: Object) => { 
       let userId = params['userId']; 
       let listingId = params['listingId']; 
       this.event = params['event']; 
       return this.checkOutInforService.getCheckoutDetails(userId, listingId); 
      }).subscribe((checkoutDetail: CheckoutUserDetail) => { 
       this.checkoutInfoDetails = checkoutDetail; 
      }); 
      console.log(this.event) //this returns undefined 

我可以看到值分配給事件以及。但是當我在上面的行後面打印一個console.log(this.event)時,它說undefiend。

問題是什麼。我怎麼能值分配給事件和組件2

+1

你就是不行。 Observable是異步的,因此console.log在分配this.event之前執行。在'subscribe'塊中移動語句。 – pixelbits

+0

如何使用該值然後 – Sajeetharan

+1

使用您的訂閱塊內的值。 – pixelbits

回答

2

我不知道這是最好的方法中使用它,但你可以嘗試:

import 'rxjs/add/observable/forkJoin' 


this.appMsgService.checkOutPageParams.asObservable() 
      .switchMap((params: Object) => { 
       return Observable.forkJoin ([ 
        this.checkOutInforService.getCheckoutDetails(userId, listingId), 
        Observable.of(params)]) 
      }).subscribe((result) => { 
       this.checkoutInfoDetails = result[0] as CheckoutUserDetail; 
       this.params = result[1]; 
       ... do with params as you wish ... 
      }); 
+0

Observable.forkJoin不是函數 – Sajeetharan

+0

您必須導入運算符 – pixelbits

+0

它的工作原理,但是當我在ui中綁定時我看不到數據,有什麼想法?

{{event}}

Sajeetharan

相關問題