2017-09-13 5 views
0

で兄弟コンポーネント間の残りの呼び出しから返されましたconsole.log内部getMyCustomerProfile'ssubscribeメソッドは返されたオブジェクトjsonを正しく出力しますが、他の2つのconsole.logundefinedを出力しますか?データの共有はこれが私の主成分であるアンギュラ4

質問2:また、上記のコンポーネントで返されたObjectを共有サービスを使用してSiblingコンポーネント(子コンポーネントではない)と共有するにはどうすればよいですか?

私は以下で試しましたが、動作しません。

共有サービス:

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

@Injectable() 
export class DataShareService { 

    private customerSource = new BehaviorSubject<Object>("default customer"); 
    currentCustomer = this.customerSource.asObservable(); 

    constructor() { } 

    changeCustomer(customer: Object){ 
    console.log("In Service: "+customer); 
    this.customerSource.next(customer); 
    } 
} 

兄弟:

import { Component, OnInit } from '@angular/core'; 
import { DataShareService } from '../data-share-service.service'; 

@Component({ 
    selector: 'app-sibling', 
    templateUrl: './sibling.component.html', 
    styleUrls: ['./sibling.component.css'] 
}) 
export class SiblingComponent implements OnInit { 

    private myCustomer: Object; 

    constructor(private dataShareService: DataShareService) { } 

    ngOnInit() { 
    this.dataShareService.currentCustomer.subscribe(customer => this.myCustomer = customer); 
    } 
} 

HomeComponentSiblingComponentの両方のためのHTMLテンプレートが返されたオブジェクトからプロパティを印刷されています

Welcome {{myCustomer?.name}} 

これは正しく印刷さHomeComponentでtでSiblingComponent。データが共有されていないことを意味します。私は何が間違っているのか分かりません。

読んでいただきありがとうございます!

答えて

1
  1. これはすべて非同期です。 subscribe(または基本的に演算子チェーンの外側)のconsole.logを使用すると、値が送出される前に呼び出されるため、undefinedになります。

  2. ただ、サービスクラスのプロパティに値を割り当てる:

    .subscribe(customer => this.myService.myCustomer = customer) 
    

    あなたはmyCustomer変更が非同期的BehaviorSubject(またはReplaySubject(1)本の場合と作るときに反応できるようにするには兄弟コンポーネントが必要な場合ケースも同じです)。入力のマーティンへ

    .subscribe(customer => this.myService.myCustomer.next(customer)) 
    
+0

は、私はあなたが言っていることでした。 AppComponentのngInit()メソッドのコメント行を見てください....しかし、それは動作していません... – Nik

+0

それはほとんどそれです。次に、 'this.myCustomer = customer;ではなくsubscribeコールバックで' changeCustomer'を呼び出す必要があります – martin

+0

getCustomerProfileのSubscribeメソッド(正しく印刷されています)内のconsole.logステートメントはthis.dataShareService.changeCustomer (this.customer); ??? – Nik

0

感謝。

private getMyCustomerProfile(){ 
    this.myService.getProfile() 
    .subscribe(
     customer => { 
      this.dataShareService.changeCustomer(customer); 
     }, 
     error => { 
      console.log("Error fetching user profile!"); 
     }); 
    } 

兄弟と次の行との主なコンポーネントの両方に同じサブスクライブ:働いていた次のように私getMyCustomerProfile方法更新

データ共有のために

this.dataShareService.currentCustomer.subscribe(customer => this.customer = customer); 
関連する問題