我有一個去服務器的父組件并獲取一個對象:// parent component@Component({ selector : 'node-display', template : ` <router-outlet [node]="node"></router-outlet> `})export class NodeDisplayComponent implements OnInit { node: Node; ngOnInit(): void { this.nodeService.getNode(path) .subscribe( node => { this.node = node; }, err => { console.log(err); } ); }在以下幾種子顯示之一中:export class ChildDisplay implements OnInit{ @Input() node: Node; ngOnInit(): void { console.log(this.node); }}似乎我無法將數據注入router-outlet??磥砦以赪eb控制臺中收到錯誤:Can't bind to 'node' since it isn't a known property of 'router-outlet'.這多少有些道理,但是我將如何執行以下操作:從父組件中獲取服務器中的“節點”數據?將我從服務器檢索到的數據傳遞到子路由器出口?似乎router-outlets工作方式不同。
3 回答

拉丁的傳說
TA貢獻1789條經驗 獲得超8個贊
Günters的回答很好,我只想指出另一種不使用Observables的方式。
在這里,盡管我們必須記住這些對象是通過引用傳遞的,所以如果您想對子對象中的對象做一些工作而不影響父對象,我建議使用Günther解決方案。但是,如果這無關緊要,或者實際上是期望的行為,我將建議以下內容。
@Injectable()
export class SharedService {
sharedNode = {
// properties
};
}
在您的父母中,您可以分配值:
this.sharedService.sharedNode = this.node;
并在您的孩子(和父母)中,將共享服務注入到您的構造函數中。如果要在該模塊中的所有組件上使用單例服務,請記住在模塊級別的提供程序數組中提供服務。另外,只需添加服務父的供應商陣列中只,那么家長和孩子將共享相同的服務實例。
node: Node;
ngOnInit() {
this.node = this.sharedService.sharedNode;
}
正如紐曼所指出的,您還可以this.sharedService.sharedNode在html模板中或使用getter:
get sharedNode(){
return this.sharedService.sharedNode;
}
- 3 回答
- 0 關注
- 1046 瀏覽
添加回答
舉報
0/150
提交
取消