[英]Typescript Mapping Values into Model Type
I have the following service: 我有以下服务:
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
}
}
In the get method of the apiService, this is what I do: 在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());
}
So I would like to parse this Json array, if there are any errors in any one of the array element, I would like to ignore it and populate the powerPlant array for the remaining valid ones! 因此,我想解析这个Json数组,如果任何一个数组元素中都存在错误,我想忽略它,并为剩下的有效数组填充powerPlant数组! Any pointers?
有指针吗?
EDIT: I tried out the suggestion as mentioned by the post below and I do get an error as shown in the screenshot: 编辑:我尝试了以下帖子中提到的建议,但确实出现了屏幕截图所示的错误:
Why is this? 为什么是这样? Is is complaining that PowerPlant is an interface and I need to provide values for the properties when I create a new instance of it?
是否抱怨PowerPlant是一个接口,并且在创建它的新实例时需要为属性提供值?
Assuming that your api service returns an array of objects, which can be considered as PowerPlant
object, here is what you can do. 假设您的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"];
}
Additionally, if your api service is not generic, then you may choose to return Observable<PowerPlant[]>
from the get
method instead of Observable<any>
. 另外,如果您的api服务不是通用的,则可以选择从
get
方法而不是Observable<any>
返回Observable<PowerPlant[]>
Observable<any>
。 To do this, you can use (res: Response) => res.json() as PowerPlant[]
. 为此,您可以使用
(res: Response) => res.json() as PowerPlant[]
。 However, this is just for the typing purpose. 但是,这仅是出于键入目的。
References: 参考文献:
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.