将数据传递到“路由器出口”子组件

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


// 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工作方式不同。


沧海一幻觉
浏览 936回答 3
3回答

拉丁的传说

Günters的回答很好,我只想指出另一种不使用Observables的方式。在这里,尽管我们必须记住这些对象是通过引用传递的,所以如果您想对子对象中的对象做一些工作而不影响父对象,我建议使用Günther解决方案。但是,如果这无关紧要,或者实际上是期望的行为,我将建议以下内容。@Injectable()export class SharedService {&nbsp; &nbsp; sharedNode = {&nbsp; &nbsp; &nbsp; // properties&nbsp; &nbsp; };}在您的父母中,您可以分配值:this.sharedService.sharedNode = this.node;并在您的孩子(和父母)中,将共享服务注入到您的构造函数中。如果要在该模块中的所有组件上使用单例服务,请记住在模块级别的提供程序数组中提供服务。另外,只需添加服务父的供应商阵列中只,那么家长和孩子将共享相同的服务实例。node: Node;ngOnInit() {&nbsp; &nbsp; this.node = this.sharedService.sharedNode;&nbsp; &nbsp;&nbsp;}正如纽曼所指出的,您还可以this.sharedService.sharedNode在html模板中或使用getter:get sharedNode(){&nbsp; return this.sharedService.sharedNode;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS