で兄弟コンポーネント間の残りの呼び出しから返されましたconsole.log
内部getMyCustomerProfile's
subscribe
メソッドは返されたオブジェクトjsonを正しく出力しますが、他の2つのconsole.log
はundefined
を出力しますか?データの共有はこれが私の主成分であるアンギュラ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);
}
}
HomeComponent
とSiblingComponent
の両方のためのHTMLテンプレートが返されたオブジェクトからプロパティを印刷されています
Welcome {{myCustomer?.name}}
これは正しく印刷さHomeComponent
でtでSiblingComponent
。データが共有されていないことを意味します。私は何が間違っているのか分かりません。
読んでいただきありがとうございます!
は、私はあなたが言っていることでした。 AppComponentのngInit()メソッドのコメント行を見てください....しかし、それは動作していません... – Nik
それはほとんどそれです。次に、 'this.myCustomer = customer;ではなくsubscribeコールバックで' changeCustomer'を呼び出す必要があります – martin
getCustomerProfileのSubscribeメソッド(正しく印刷されています)内のconsole.logステートメントはthis.dataShareService.changeCustomer (this.customer); ??? – Nik