我有一个去服务器的父组件并获取一个对象:// 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。看来我在Web控制台中收到错误: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 关注
- 999 浏览
添加回答
举报
0/150
提交
取消