如何将数据分配给组件中的变量?

How to assign data to variable in component?

我有核心组件:

export class AppComponent implements OnInit {
   constructor() {

       const toast: any = {
        type: exception.type,
        body: ToasterRenderComponent.messages = ["44"],
        bodyOutputType: BodyOutputType.Component
      };

      this.toasterService.pop(toast);
   }
}

在构造函数中,我尝试填充对象 toast 并将数据分配给组件的变量 ToasterRenderComponent:

ToasterRenderComponent.messages = ["44"]

组件 ToasterRenderComponent 有 public 属性 messages,但它对我不起作用。

在处理跨组件数据传输时,根据组件之间的关系,我想到了两种主要的方法。

  • 如果组件视图没有嵌套(不是父子视图),那么自然的方法是创建一个 Angular service.

  • 如果组件嵌套,通常会通过template data binding.

  • 传递数据

当然有变通方法,但是为了确保 Angular 正确销毁组件,我建议坚持文档中的说明。

试试这个

import { Router } from '@angular/router';    
export class AppComponent implements OnInit {
   constructor(private router: Router) {    
       const toast: any = {
        type: exception.type,
        body: ToasterRenderComponent.messages = ["44"],
        bodyOutputType: BodyOutputType.Component
      };    
      this.router.config.find(r => r.component== ToasterRenderComponent).data = toast;
   }
}

组件 "ToasterRenderComponent"

import { ActivatedRoute } from '@angular/router';    
export class ToasterRenderComponent implements OnInit {
  toasterObject: any;
  constructor(private router: ActivatedRoute) { }
  ngOnInit() {
    this.router.data.subscribe(r=>this.toasterObject=r);
  }
}