我会做一个Service
注入到共享同一数据的所有部件,像这样的:
@Injectable()
export class SharedDataService {
someData:Object={}
constructor() {
}
}
然后,在你的组件,你可以聆听到为了使用Router
服务导航改变更新组件和用户界面中的数据。
import {Component,OnInit} from '@angular/core';
import {NavigationEnd, Router} from "@angular/router";
import {SharedDataService} from "../shared-data.service";
@Component({
selector: 'profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class Profile implements OnInit {
someData:Object;
constructor(private sharedDataService: SharedDataService, private router:Router) {
this.someData = this.sharedDataService.someData;
this.router.events.subscribe((val)=>{
if(val instanceof NavigationEnd){
//update the shared data when this page is being navigated to
this.someData=this.sharedDataService.someData;
}
});
}
}
看一看[这一个](http://stackoverflow.com/questions/35478994/angular-2-passing-object-via-route-params-possible)。使用提供者在“组件”之间共享数据 – John
看起来像处理这个问题的一般方法是(a)在组件之间创建共享服务并在它们之间绑定变量数据,或者如果您不需要数据绑定:(b )通过路由参数传递值 –