2016-09-30 43 views
1

我正在嘗試製作一個列出5個城市及其當前天氣的天氣應用程序。當你點擊一個城市時,它會轉到一個詳細視圖,顯示該城市的5天預報。如何將JSON數據綁定到我的類屬性

現在我有一個weatherItem類:

export class WeatherItem { 
    city: string; 
    description: string; 
    temperature: number; 
} 

*這是我的WeatherService是得到了5個城市的當前天氣信息的方法:

fetchCurrent(){ 
    return Observable.forkJoin(
     this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Chicago&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
     (response) => response.json()), 
    this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Dallas&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
     (response) => response.json()), 
    this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Milwaukee&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
     (response) => response.json()), 
    this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Seattle&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
     (response) => response.json()), 
    this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Washington&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
     (response) => response.json()) 
); 
    } 

,這是方法我在使用我的weatherService中的fetchCurrent()方法的WeatherComponent中調用了我的weatherService

getWeather(): void { 
    this.weatherService.fetchCurrent() 
    .subscribe(data => this.weatherItems = data); 
    } 

它成功地從openweathermap.org但在我 WeatherComponent抓住當前天氣數據我目前顯示的數據是這樣的:

<ul class="weatherItems"> 
    <li *ngFor="let weatherItem of weatherItems" class="box" (click)="gotoDetail(weatherItem)"> 
     <div class="col-1"> 
     <h3>{{weatherItem.name}}</h3> 
     <p class="info">{{weatherItem.weather[0].description}}</p> 
     </div> 
     <div class="col-2"> 
     <span class="temperature">{{weatherItem.main.temp}}° F</span> 
     </div> 
    </li> 
    </ul> 

如何採取JSON數據並將其正確映射到我的看法?比如我有

{{weatherItem.city}}

當我使用模擬數據,但現在我不得不使用JSON數據,我不能讓顯示視圖前

城市名稱正確,除非我用

{{weatherItem.name}}

是否有角2的方式從JSON「名稱」數據綁定到我的天氣Item.city屬性?

+1

數據看起來像什麼? – longbow

+0

您是否在控制檯中看到任何錯誤?你如何接收數據並將其轉換爲JSON? – m4ttsson

+0

我在控制檯中看不到任何錯誤,但我希望在視圖模板中顯示我的數據爲{{weatherItem.city}},而不是{{weatherItem.name}},這是JSON數據屬性。 我剛剛添加了調用http.get的代碼片段。這就是我目前正在接收我的5個城市的數據的方式。 – Xenohs

回答

0

首先,如果你的WeatherItem只是後端級車型就應該是這樣的(模型類應該有相同的屬性名的JSON):

export class WeatherItem { 
    constructor(weather: Weather, 
       base: string, 
       id: number, 
       name: string, 
       cod: number) {} 
} 

export class Weather { 
    constructor(id: number, 
       main: string, 
       description: string, 
       icon: string){} 
} 

第二個,你weatherItems應該聲明如下即:

public weatherItems: Array<WeatherItem>; // or just weatherItem: Weather if your json just return single object 

當然,你可以創建你的JSON屬性(主,風,雨ECT)的其餘部分完整的模型,但如果你不需要使用它沒有必要的。

相關問題