在组件之间传递数据被另一个组件取代,我假设有一个数据可以被多个组件读取和修改。要达到此目的,您可以使用router
,在angular service
,dependency injection
,behavior subject
和subscription
的帮助下。
首先创建一个angular service
与behaviorSubject属性作为数据:
@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
}
}
现在,当您使用路由器这两个组件的路由,每当用户导航到一个组件,该组件将获得最新的数据值。
'https:// stackoverflow.com/a/45668262/2708210'可能重复# –