简体   繁体   English

以角度在组件之间传递数据

[英]pass data between components in angular

I am trying to add a dashboard component and try pass user details to it.我正在尝试添加仪表板组件并尝试将用户详细信息传递给它。 I declare in dashboard.component.ts user: User, which has his own model and in ng on it i declared it as:我在dashboard.component.ts 中声明user: User,它有自己的模型,在ng 中我将其声明为:

this.route.data.subscribe(data => {
      this.user = data['user'];
    });

now when i call in in html as {{user.firstName}} i get this error现在,当我以 {{user.firstName}} 的身份在 html 中调用时,我收到此错误

ERROR TypeError: Cannot read property 'firstName' of undefined
    at Object.eval [as updateRenderer] (DashboardTopbarComponent.html:213)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:36090)
    at checkAndUpdateView (core.js:35073)
    at callViewAction (core.js:35433)
    at execComponentViewsAction (core.js:35361)
    at checkAndUpdateView (core.js:35074)
    at callViewAction (core.js:35433)
    at execComponentViewsAction (core.js:35361)
    at checkAndUpdateView (core.js:35074)
    at callViewAction (core.js:35433)

This is my dashboard.component.ts file这是我的dashboard.component.ts 文件

export class DashboardTopbarComponent implements OnInit {
  user: User;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.user = data['user'];
    });
  }
}

You have to remember, that js is a single threaded language.你必须记住, js是一种单线程语言。 Even if you subscribed to the data and as a callback pass a function which will set your user , the user will be set only after Angular finish rendering your component, so you are trying to get field firstName , while your object is null/undefined.即使您订阅了data并作为回调传递了一个将设置您的user的函数,用户也只会在Angular完成渲染您的组件后设置,因此您正在尝试获取字段firstName ,而您的对象为空/未定义。 What you should do, is grab the user from snapshot and then subsribe to data (yes, it will be called twice but you will be handling case when user changes somehow), or wrap your template with ngIf .您应该做的是从snapshot获取user ,然后订阅data (是的,它会被调用两次,但您将处理用户以某种方式更改的情况),或者用ngIf包装您的模板。

You should initialize user in controller您应该在控制器中初始化用户

user:User = {}

or you should check if user is exist in HTML file, try this或者你应该检查用户是否存在于 HTML 文件中,试试这个

{{user && user.firstName}} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM