将数据传递到“路由器出口"子组件 [英] Passing data into "router-outlet" child components

查看:30
本文介绍了将数据传递到“路由器出口"子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a parent component that goes to the server and fetches an object:

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

在几个儿童展示之一中:

And in one of several childdren display:

export class ChildDisplay implements OnInit{

    @Input()
    node: Node;

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

}

似乎我不能将数据注入router-outlet.看起来我在网络控制台中收到错误:

It doesn't seem I can just inject data into the router-outlet. It looks like I get the error in the web console:

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

这有点道理,但我该怎么做:

This somewhat makes sense, but how would I do the following:

  1. 从服务器中获取节点"数据,从父级内部组件?
  2. 将从服务器检索到的数据传递到子路由器插座?

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

It doesn't seem like router-outlets work the same way.

推荐答案

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

只是无效的.路由器添加的组件作为<router-outlet>的兄弟添加并且不会替换它.

is just invalid. The component added by the router is added as sibling to <router-outlet> and does not replace it.

另见 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);
    }
}

这篇关于将数据传递到“路由器出口"子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆