2017-08-25 61 views
0

我有以下服務:打字稿映射值到型號類型

import { Component } from '@angular/core'; 
import { ApiService } from './shared/api.service'; 
import {PowerPlant} from './shared/models/powerplant.model'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    powerPlants: PowerPlant[]; 

    constructor(private apiService: ApiService) { 
    } 

    allPowerPlants(onlyActive: boolean = false, page: number = 1): void { 
    const path = `$/powerPlants?onlyActive${onlyActive}&page${page}`; 
    this.apiService.get(path).map() // TODO: parse and set the JSON to my model 
    } 
} 

在apiService的get方法,這是我做的:

get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> { 
    return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params }) 
     .catch(this.formatErrors) 
     .map((res: Response) => res.json()); 
    } 

所以我想解析這個Json數組,如果在任何一個數組元素中有任何錯誤,我想忽略它併爲剩餘的有效數組填充powerPlant數組!任何指針?

編輯:我嘗試了建議,如下面的文章中提到,我做得到一個錯誤的截圖所示:

enter image description here

這是爲什麼?是抱怨PowerPlant是一個接口,當我創建一個新的實例時,我需要爲屬性提供值?

+0

那麼如何檢測數組元素之一是否有錯誤? –

+0

我不知道!你能幫我指點一下我怎麼能做到這一點? – sparkr

+0

我在這裏有點困惑。所以一些數組元素可能有錯誤,但是你不確定什麼可以被視爲錯誤?由於我不是一個角度用戶,我建議你在'this.apiService.get(path).map()'的'map'方法中使用回調函數,並將傳遞給回調函數的值賦給'powerPlants ';你也可以在回調函數中使用'console.log'來檢查一切是否正確。 –

回答

1

假設您的api服務返回一個對象數組,可以將其視爲PowerPlant對象,這裏是您可以執行的操作。

powerPlants: PowerPlant[] = []; //initialize the array. 

allPowerPlants(onlyActive: boolean = false, page: number = 1): void { 
    const self = this; 
    const path = `$/powerPlants?onlyActive${onlyActive}&page${page}`; 
    this.apiService.get(path).subscribe(
     powerplants:any[] => { 
      powerplants.forEach(item=>{ 
       if(isPowerPlant(item)){ 
        // cast the item as PowerPlant 
        self.powerPlants.push(item as PowerPlant); 
       } 
      }); 
     }, 
     err=> { 
      // handle error 
     }); 
} 

// define the type guard 
isPowerPlant(item:any):item is PowerPlant { 
    // check for the required properties of PowerPlant here and return true/false. 
    // example: 
    return item["powerplantProp1"] && item["powerplantProp2"]; 
} 

此外,如果你的API服務是不通用的,那麼你可以選擇從get方法而不是Observable<any>返回Observable<PowerPlant[]>。 爲此,您可以使用(res: Response) => res.json() as PowerPlant[]。 但是,這只是爲了打字的目的。

參考文獻:

  1. https://scotch.io/tutorials/angular-2-http-requests-with-observables
  2. https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

希望這有助於。

+0

我嘗試了您的建議,但看起來像我有一個錯誤!我已經編輯過我的帖子! – sparkr

+0

@sparkr如果'PowerPlant'是一個接口,那麼你不能使用'new'來實例化它。在這種情況下,'self.powerPlants.push(item PowerPlant);',或者簡單地'self.powerPlants.push(item);'也應該足夠。 –

+0

是的,PowerPlant是我的例子中的一個接口。你能更新你的asnwer嗎? – sparkr