2017-03-02 2 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>(); 

    } 

} 

Iが別のコンポーネントに以下のパラメータを渡すためにこのサービスを使用して、

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

私がデバッグするときのイベントに、これは2番目のコンポーネントの値を取得する方法です。

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

をなし、あなたがすることはできません。 Observablesは非同期なので、this.eventが割り当てられる前にconsole.logが実行されます。ステートメントを '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

をインポートする必要がありますが、私はあなたがデータを見ることができません。

{{event}}

Sajeetharan

関連する問題