簡體   English   中英

angular 4 無法讀取未定義的屬性“id”

[英]angular 4 cannot read property 'id' of undefined

我正在嘗試使用 angular 4 來調用一個虛擬的 web api,這是我的組件

export class AppComponent {
    title = 'app';
    url = 'https://api.ipify.org/?format=json';
    results: any;

    constructor(private http: Http) {
        this.getData().subscribe(data => {
            this.results = data.json();
        })
    }

    getData() {
        return this.http.get(this.url);
    }

}


但是當我嘗試顯示它時,我得到了結果,但也出現了錯誤屏幕

ERROR TypeError: Cannot read property 'ip' of undefined

我想了解的是為什么顯示它,因為一瞬間后數據顯示良好。

在您的*ngFor ,您可以將其更改為*ngFor="let r of results | async"

您的問題是數據還不存在,因此它無法讀取 id 屬性。

如果你使用異步管道,它應該在顯示之前等待數據到來。

使用 Elvis Operator 代替 i:e safe operator

{{results?.ip}} 

如果將組件添加到導入數組而不是聲明數組,也會出現此錯誤。

@NgModule({
  imports: [
    ...,
    someComponent
  ],

  declarations: [...],
})
export class MainModule { }

應該

@NgModule({
  imports: [
    ...,
  ],

  declarations: [...,someComponent],
})
export class MainModule { }

將 {{results}} 放入您的 html 部分。 你會看到服務器給你的價值。

也許您應該在獲取值時使用 *ngfor 並在其上使用異步管道以正確顯示它

改變這個

import 'rxjs/add/operator/map';


this.getData().subscribe(data => {
  this.results = data;
 });
}

getData() {
     return this.http.get(this.url).map(resp => resp.json());
}

並將其添加到模板中

*ngIf="results" 
import 'rxjs/add/operator/map';


this.getData().subscribe(data => {
  this.results = data;
 });
}

getData() {
     return this.http.get(this.url).map(resp => resp.json());
}

HTML部分

*ngFor="let r of results | async"
 <p>{{r}}</p>

如果你有多個屬性,你可以使用一個類並將它們注入到那里,那就沒問題了。 否則,如果您只有一個變量並且希望顯示它,請使用安全導航運算符user?.name

暫無
暫無

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

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