簡體   English   中英

了解如何調用REST Api並在Angular 2中顯示響應中的數據

[英]Understanding how to call a REST Api and displaying the data from the response in Angular 2

我是Angular 2和Typescript的新手,所以請原諒我這個問題,但是在成功調用REST Api之后我無法理解如何使用數據。 我為我的例子做了一個plunker ,所以更容易解釋我要做的事情。

查看示例時請忽略未使用的導入。

調用函數getWeather工作正常。

getWeather(query) {
        const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';
        return this.http
            .get(endpoint)//, {search: searchParams})
            .map(res => res.json().main)
            .subscribe(res => console.log('weather json response = ' + JSON.stringify(res))
            );
    }

但是如何存儲數據呢? 我的意思是我必須創建一個類似json響應的對象,並使用if如何顯示數據以及如何?

編輯: 是我的代碼的一個工作示例。

還原數據時,只需使用this關鍵字將它們設置為組件的屬性即可。

在HTTP請求的情況下,當調用使用subscribe方法注冊的第一個回調時,數據就在那里。

使用箭頭函數定義此回調允許通過this關鍵字使用組件實例(在本例中為contextual)。

getWeather(query) {
  const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';
  return this.http
      .get(endpoint)//, {search: searchParams})
      .map(res => res.json().main)
      .subscribe(res => {
        this.weather = data;
       });
}

然后模板可以引用這些屬性來顯示帶有ngFor,{{...}}或插值的數據。 小心處理可觀察的異步方面,例如異步管道,ngIf或Elvis運算符(?)。

<div>{{weather?.someProperty}}</div>

您確實可以創建一個類來模擬json響應並轉換為它,或者只是將其用作any並使用點符號來提取和顯示數據。 只需添加一個字段並為其分配響應即可。 像這樣:

countryData: any;

getWeather(query) {
    const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';
    return this.http
        .get(endpoint)//, {search: searchParams})
        .map(res => res.json().main)
        .subscribe(res => this.countryData = res)
        );
}

如果你想事先將它建模為一個類,你也可以這樣做:

countryData: Country;

getWeather(query) {
    const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';
    return this.http
        .get(endpoint)//, {search: searchParams})
        .map(res => res.json().main)
        .subscribe(res => this.countryData = <Country>res)
        );
}

但請注意,如果您使用第二種方法並強制轉換為Country或您為其命名的任何名稱,那么它將不具有您在該類上定義的任何可用方法。

暫無
暫無

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

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