gpt4 book ai didi

angular - 将数据传递到 "router-outlet"子组件

转载 作者:太空狗 更新时间:2023-10-29 16:45:41 25 4
gpt4 key购买 nike

我有一个父组件去服务器并获取一个对象:

// 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);
}
);
}

并且在几个 child 展示之一中:

export class ChildDisplay implements OnInit{

@Input()
node: Node;

ngOnInit(): void {
console.log(this.node);
}

}

我似乎无法将数据注入(inject)router-outlet。看起来我在 Web 控制台中收到了错误:

Can't bind to 'node' since it isn't a known property of 'router-outlet'.

这有点道理,但我将如何执行以下操作:

  1. 从父节点中从服务器获取“节点”数据组件?
  2. 将我从服务器检索到的数据传递到子路由器导出?

router-outlets 的工作方式似乎不同。

最佳答案

<router-outlet [node]="..."></router-outlet> 

只是无效的。路由器添加的组件作为兄弟添加到 <router-outlet>并且不会取代它。

另见 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

@Injectable() 
export class NodeService {
private node:Subject<Node> = new BehaviorSubject<Node>([]);

get node$(){
return this.node.asObservable().filter(node => !!node);
}

addNode(data:Node) {
this.node.next(data);
}
}
@Component({
selector : 'node-display',
providers: [NodeService],
template : `
<router-outlet></router-outlet>
`
})
export class NodeDisplayComponent implements OnInit {
constructor(private nodeService:NodeService) {}
node: Node;
ngOnInit(): void {
this.nodeService.getNode(path)
.subscribe(
node => {
this.nodeService.addNode(node);
},
err => {
console.log(err);
}
);
}
}
export class ChildDisplay implements OnInit{
constructor(nodeService:NodeService) {
nodeService.node$.subscribe(n => this.node = n);
}
}

关于angular - 将数据传递到 "router-outlet"子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41451375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com