簡體   English   中英

以角度在組件之間傳遞數據

[英]pass data between components in angular

我正在嘗試添加儀表板組件並嘗試將用戶詳細信息傳遞給它。 我在dashboard.component.ts 中聲明user: User,它有自己的模型,在ng 中我將其聲明為:

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

現在,當我以 {{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)

這是我的dashboard.component.ts 文件

export class DashboardTopbarComponent implements OnInit {
  user: User;

  constructor(private route: ActivatedRoute) {}

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

你必須記住, js是一種單線程語言。 即使您訂閱了data並作為回調傳遞了一個將設置您的user的函數,用戶也只會在Angular完成渲染您的組件后設置,因此您正在嘗試獲取字段firstName ,而您的對象為空/未定義。 您應該做的是從snapshot獲取user ,然后訂閱data (是的,它會被調用兩次,但您將處理用戶以某種方式更改的情況),或者用ngIf包裝您的模板。

您應該在控制器中初始化用戶

user:User = {}

或者你應該檢查用戶是否存在於 HTML 文件中,試試這個

{{user && user.firstName}} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM