這聽起來像你想在多個路由組件之間共享數據。一種常見的模式是構建一個服務,該服務共享/注入您想共享該數據的任何組件。然後,您可以通過每個組件的服務調用寫入或讀取數據來獲取相同的數據。
BTW承諾在Angular2中工作得很好。
a.component.ts
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service.ts';
@Component({
selector: 'my-component-a',
templateUrl: 'a.component.html'
})
export class ComponentA implements OnInit {
constructor (private sharedService: SharedService) {}
ngOnInit() {
this.sharedService.write('Hello from component A');
}
}
b.component.ts
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service.ts';
@Component({
selector: 'my-component-b',
templateUrl: 'b.component.html'
})
export class ComponentA implements OnInit {
constructor (private sharedService: SharedService) {}
ngOnInit() {
let message = this.sharedService.read();
// message should now be the string `Hello from component A'
}
}
shared.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
private message: string = null;
constructor() {}
read() {
return this.message;
}
write (newMessage: string) {
this.message = newMessage;
}
}
ngrx/store也是另一種選擇。這裏的想法是,您有一個應用程序狀態,您可以在其中存儲所有應用程序數據。您可以打電話到商店取數據,或者您可以撥打減少人數這將更新您的應用程序數據。單是這個話題就很多,所以我強烈建議在嘗試這種方法之前先閱讀一下。
對不起長時間的寫作,但又想補充一點。 :) 在Angular2中,有一個resolve guard
可用於預取任何路由的數據。它仍然需要某種可以從中獲取數據的服務。但是如果你希望你的視圖能夠在你看到的時候做好渲染的準備,那麼這很好。 Here's more info about that