2017-08-02 42 views
0

在Angular 4.3中使用新的HttpClient模塊時,從REST api獲取單個記錄時出現控制檯錯誤。我在IDE中沒有收到任何linter錯誤,頁面渲染和變量顯示。我是否聲明瞭錯誤的變量類型?Angular 4.3 HttpClient控制檯錯誤

import { Component, OnInit } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 

interface Hero { 
    id: number; 
    name: string; 
} 

@Component({ 
    selector: 'app-root', 
    template: ` 
      My name is {{hero.name}} and my id is {{hero.id}} 
    `}) 

export class AppComponent implements OnInit { 
    hero: Hero; 

    constructor(private http: HttpClient) { } 

    getOne() { 
    this.http.get<Hero> 
     ('http://0.0.0.0:3000/api/heroes/23') 
     .subscribe(data => { 
     this.hero = data; 
     }); 
    } 
    ngOnInit() { 
    this.getOne(); 
    } 
} 

回報:我的名字是Bombasto,我的ID是13

與控制檯錯誤:

TypeError: undefined is not an object (evaluating '_co.hero.name') 

而第一個鍵產生一個錯誤,第二個沒有(例如沒有錯誤爲hero.id)。如果我切換順序(hero.id是第一個,所以輸出是「我的ID是13,我的名字是Bombasto),我得到的是hero.id的錯誤,而不是hero.name。

隨着頁面呈現,我可以忽略控制檯錯誤並繼續前進,我試圖通過將代碼剝離到最低限度以瞭解其工作原理,並且我不想開發任何編碼習慣。

此外,與GETALL()相同的例子使用沒有任何錯誤:

heroes: Hero[]; 
getAll() { 
     this.http.get<Hero[]> 
      ('http://0.0.0.0:3000/api/heroes') 
      .subscribe(data => { 
      console.log(data); 
      this.heroes = data; 
      }); 
     } 

感謝,

+0

嘗試初始化英雄或將* ngIf =「hero」添加到您的節點。 –

+0

這兩個選項都可以清除錯誤。或者,我也可以'.subscribe(data => {this.hero.id = data.id; this.hero.name = data.name;}以避免錯誤,但是試圖最小化我的代碼。謝謝, – nicolas0001

+0

* ngIf =「英雄」似乎是最乾淨的答案,因爲它不會在HTTP調用返回之前在屏幕上刷新已初始化的變量。 – nicolas0001

回答

0

在HTTP呼叫返回之前,hero未定義。 Angular4有一個很好的模板測試器。如果您將{{hero.name}}更改爲{{hero?.name}},那麼一旦角色驗證存在hero,角將只嘗試訪問.name

您還需要做同樣的{{hero.id}},將其更改爲{{hero?.id}}

+0

您是否建議當您錯誤地要求某件事情發生時Angular不再崩潰和灼傷'還沒有存在嗎? – wolfhoundjesse

+0

如果你不把'?'放在那裏,它會崩潰並燒壞。{{hero.name}}'會給「英雄不是對象」錯誤,除非你把'{ {hero?.name}}',其實質上相當於'{{hero && hero.name}}' –

+0

我問的唯一原因就是之前沒有任何東西會呈現,根據OP的說法,Angular抱怨,但是這樣做反正 – wolfhoundjesse

0

貓王操作?.將修復錯誤,但取決於如何快速的數據加載後,你可能會注意到,在第一,文本將會出現空格:My name is and my id is(如果你使用大量數據或從外部服務器上下載,你一定會注意到這一點)。另一種解決方案是隱藏文本的整個塊,直到hero有一個值,使用*ngIf

template: ` 
    <span *ngIf="hero">My name is {{hero.name}} and my id is {{hero.id}}</span> 
` 

這也將避免你得到的錯誤,因爲該元素的內容是不是在所有裝直到條件成立。