2016-09-27 69 views
0

我知道如何使用NgFor呈現模板中的對象列表,但我無法找到顯示不在數組中的單個對象的任何信息。如何在模板中顯示單個對象

我有一個返回的用戶配置文件,通過我的ProfileService的API終點:

find() { 
    return this.http.get('/api/user/22/profile.json'); 
} 

我的組件設置這樣的:

export class ProfileListComponent implements OnInit { 
    profile: any; 

    constructor(private profileService: ProfileService) { } 

    loadProfile() { 
    this.profileService.find() 
     .subscribe(response => this.profile = response.json()); 
    } 

    ngOnInit() { 
    this.loadProfile(); 
    } 

} 

在我的模板,我不想要使用NgFor,我只想顯示個人資料的屬性,如:

{{ profile.name }} 

我該如何實現?現在,我收到一個未定義的錯誤,就像配置文件不存在一樣。

+1

您嘗試過什麼?具體來說,你似乎確切知道如何完成你的任務,那又怎麼了? – tcooc

+0

@tcooc我還在學習,所以我不能告訴你更多的東西比我在控制檯中發生錯誤時說:「無法讀取未定義的屬性名稱」 –

回答

1

profile字段保持未定義狀態,直到http響應返回並且調用初始化回調的回調。這就是你得到這個錯誤的原因。使用ngIf可避免在尚未使用的配置文件中使用模式,或使用

{{ profile?.name }} 
+0

就是這樣!謝謝! –

相關問題