我有一个问题。为什么带有Angular的Typescript不能正确映射对象中的对象列表?
在我的场景中,我有一个包含员工和产品的公司。 TypeScript的模型如下所示:
import { Product } from "./product";
import { Employee } from "./employee"; //my own classes
export class Company {
id: number; //my own class
name: string;
products: Product[] = []; //company have products and employees
employees: Employee[] = [];
}
我的WebApi,即ASP .NET WebApi2
向我返回了如下所示的JSON:
{
"employees": [
{
"userId": "98560542-0202-48b6-b8c5-cde945151527",
"joinDate": "2015-07-20T00:00:00",
"companyId": 29
}
],
"products": [
{
"id": 29,
"name": "xxx",
"companyId": 29
},
{
"id": 30,
"name": "zzz",
"companyId": 29
}
],
"id": 29,
"name": "companyName8",
}
形成上面我得到的响应employees
和products
,而没有类型。其中的项目只有对象。为避免这种情况,我将以下行添加到了subscribe()
方法中(我在其中获得company
):
company: Company = new Company();
comanyProducts: Products[] = [];
for (const item of this.company.products) {
this.companyProducts.push(Object.assign(new Product(), item));
//this.companyProducts its a new list to store
//company's products with proper type of Product
}
当我有10或100种产品时,这没什么大不了的,但是当我们列出10000或100000件产品时该怎么办?为什么我不能只使用它(从中我只得到Object
的列表,而不是我想要的Product
的列表):
this.companyProducts = this.company.products
//it is in my subscribe
我做错了什么以及如何解决?
编辑
我的API FUnc无法处理对象中的对象列表:
public getObject<T>(
type: new () => T,
id: number
): Observable<DataResponse<T>> {
const url = `${this.getUrl(type)}${id}`;
return this.http.get<T>(url).pipe(
map((input: Object, indx: number) => {
const inputObject: T = input as T;
const outputObject = new type();
Object.assign(outputObject, inputObject);
return new DataResponse(outputObject);
}),
catchError(this.handleError<T>(`get${type.name} id=${id}`))
);
}
//i call it like this: this.dataService.getObject(Company).subscribe(resulut => { this.list = result.object});
然后在订阅中,我只在循环中进行Object.assign