如何將數(shù)據(jù)傳遞給Angular路由組件?在我的一個Angular 2路線的模板(FirstComponent)中,我有一個按鈕first.component.html<div class="button" click="routeWithData()">Pass data and route</div>我的目標是實現(xiàn):按鈕單擊 - >路由到另一個組件,同時保留數(shù)據(jù),而不使用其他組件作為指令。這就是我試過的......第一種方法在同一視圖中,我存儲基于用戶交互收集相同的數(shù)據(jù)。first.component.tsexport class FirstComponent {
constructor(private _router: Router) { }
property1: number;
property2: string;
property3: TypeXY; // this a class, not a primitive type
// here some class methods set the properties above
// DOM events
routeWithData(){
// here route
}}一般情況下我路由SecondComponent通過 this._router.navigate(['SecondComponent']);最終傳遞數(shù)據(jù) this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);而帶參數(shù)的鏈接的定義是@RouteConfig([
// ...
{ path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent} )]這種方法的問題是我猜我無法傳遞復雜數(shù)據(jù)(例如像property3這樣的對象)in-url;第二種方法另一種方法是在FirstComponent中包含SecondComponent作為指令。 <SecondComponent [p3]="property3"></SecondComponent>但是我想要路由到該組件,而不是包含它!第三種方法我在這里看到的最可行的解決方案是使用服務(例如FirstComponentService)將數(shù)據(jù)(_firstComponentService.storeData())存儲在FirstComponent中的routeWithData()上在SecondComponent中的ngOnInit()中檢索數(shù)據(jù)(_firstComponentService.retrieveData())雖然這種方法似乎完全可行,但我想知道這是否是實現(xiàn)目標的最簡單/最優(yōu)雅的方式。一般來說,我想知道我是否缺少其他可能的方法來在組件之間傳遞數(shù)據(jù),特別是在代碼量較少的情況下
3 回答

慕容3067478
TA貢獻1773條經(jīng)驗 獲得超3個贊
我想因為我們在角度2中沒有$ rootScope類似于角度1.x. 我們可以使用angular 2共享服務/類,而在ngOnDestroy中將數(shù)據(jù)傳遞給服務,并在路由后從ngOnInit函數(shù)中的服務獲取數(shù)據(jù):
這里我使用DataService來共享英雄對象:
import { Hero } from './hero';export class DataService { public hero: Hero;}
從第一頁組件傳遞對象:
ngOnDestroy() { this.dataService.hero = this.hero; }
從第二頁組件獲取對象:
ngOnInit() { this.hero = this.dataService.hero; }
這是一個例子:plunker
- 3 回答
- 0 關(guān)注
- 572 瀏覽
添加回答
舉報
0/150
提交
取消