我會做一個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 )通過路由參數傳遞值 –