別のコンポーネントで置き換えられるコンポーネント間でデータを渡すと、複数のコンポーネントによって読み取られ、変更される可能性のあるデータがあるとします。これを実現するために、あなたはangular service
、dependency injection
、behavior subject
、およびsubscription
の助けを借りて、router
を使用することができます。
まず、データとしてbehaviorSubjectプロパティでangular service
を作成します。
@Injectable()
export class DataService()
{
public data: Subject<any> = new BehaviorSubject<any>(null);
changeData(newData: any) {
this.data.next(newData); // this will update the value of the `data` with `newData`, and any component which subscribe to `data` will get the updated value of `data`.
}
}
注射用サービスは、ユーザーが他のコンポーネントからコンポーネントへとジャンプしながらデータを保持することができます。次のステップは、データを必要とするコンポーネントにこのサービスを注入することです。のは、例えばデータが必要ComponentA
とComponentB
を見てみましょう:
@Component({
selector: 'component-a'
providers: [DataService],
templateUrl: `component-a.html`
)}
export class ComponentA {
constructor(private dataService: DataService) {
this.dataService.data.subscribe((value) => {
// here, component A able to always get the updated value of the data when its value is changed.
});
}
}
そしてComponentBため、のこのコンポーネントは、交換する能力(または更新)データを持っているとしましょう:
今
@Component({
selector: 'component-b'
providers: [DataService],
templateUrl: `component-b.html`
)}
export class ComponentB {
constructor(private dataService: DataService) {
this.dataService.data.subscribe((value) => {
// here, component B able to always get the updated value of the data when its value is changed.
});
}
changeData(newData: any) {
this.dataService.changeData(newData); // this call will update the value of the data which DataService keeps, therefore when user jump to ComponentA, ComponentA will retrieve the updated value from `this.dataService.data`'s subscription
}
}
、あなたが使用している場合ルータはこれらの2つのコンポーネントをルーティングし、ユーザが1つのコンポーネントにナビゲートするたびに、そのコンポーネントはデータの最新の値を取得します。 `HTTPSの
が重複する可能性:// stackoverflow.com// 45668262/2708210' –