问题描述
我在组件中写入特定数据时遇到问题。我从 api 加载了父母数据(品牌)但孩子数据(模型)我不知道如何从 api 加载。我从服务器到控制台获取的数据:
这显示我在监视器上:。
在控制台中我有这个错误:错误类型错误:无法读取未定义的属性“地图”。
你知道如何解决这个问题吗?感谢您的帮助。
我的代码:
app.component.ts
# Approach 1: Expected output received here:
df_initial %>%
mutate_at(vars(-index_name,-totalReturn_daily),~ na.locf(.,na.rm = FALSE)) %>%
filter(index_name == "TPX Index")
# Output
Date index_name index_level totalReturn_daily
<date> <chr> <dbl> <dbl>
1 2021-02-23 TPX Index NA 0
2 2021-02-24 TPX Index 1903. -1.82
3 2021-02-25 TPX Index 1926. 1.24
4 2021-02-26 TPX Index 1864. -3.21
5 2021-02-27 TPX Index 1864. 0
6 2021-02-28 TPX Index 1864. 0
# Approach 2: Did not receive expected output here
df_initial %>%
ungroup() %>%
mutate(across(
.cols = -c(index_name,totalReturn_daily),.fns = ~ na.locf(.,na.rm = FALSE)
)) %>%
filter(index_name == "TPX Index")
# Output
Date index_name index_level totalReturn_daily
<date> <chr> <dbl> <dbl>
1 2021-02-23 TPX Index 3881. 0
2 2021-02-24 TPX Index 1903. -1.82
3 2021-02-25 TPX Index 1926. 1.24
4 2021-02-26 TPX Index 1864. -3.21
5 2021-02-27 TPX Index 44593. 0
6 2021-02-28 TPX Index 44593. 0
app.component.html
vehicleLists: VehicleLists[] = [];
constructor(
private vehicleService: VehicleService,private router: Router,private vehiclelistadapter: listadapter,) {
}
ngOnInit(): void {
this.getLists();
}
public getLists() {
this.vehicleService.getVehicleLists().subscribe(({ brands,models }) => {
console.log(brands);
this.vehicleLists = brands;
models.map(model =>
this.vehicleLists.push(this.vehiclelistadapter.adapt(model)));
});
}
lists.ts - 模型
<div *ngFor="let item of vehicleLists">
<p>{{item.id}} - {{item.name}}</p>
<p>{{item.models}}</p>
</div>
vehicle-list.adapter.ts
export class VehicleLists {
id: string;
name: string;
models: VehicleModel[];
}
export class VehicleModel {
name: string;
description: string;
}
vehicle.service.ts
export class listadapter implements Adapter<VehicleLists> {
adapt(item: any): VehicleLists {
const obj = new VehicleLists();
obj.name = item.name;
obj.id = item.id;
obj.models = item.models;
return obj;
}
}
解决方法
我相信错误 ERROR: ERROR TypeError: Cannot read property 'map' of undefined
来自于 models.map
:
public getLists() {
this.vehicleService.getVehicleLists().subscribe(({ brands,models }) => {
console.log(brands);
this.vehicleLists = brands;
models.map(model =>
this.vehicleLists.push(this.vehicleListAdapter.adapt(model)));
});
}
您对 models
的引用是 undefined
,因为它嵌套在 brands
数组中的每个对象内,并且无法在订阅 { brands,models }
中解包。
brands
是一个包含多个对象的数组,比如一个 brand
,每个对象都有一个键 models
,它也是一个对象数组,我们可以称之为 {{1} }.您需要遍历品牌数组才能找到每个模型数组。
这样的事情怎么样?
model
注意:您正在推送到 public getLists() {
this.vehicleService.getVehicleLists().subscribe(({ brands }) => {
console.log(brands);
this.vehicleLists = brands;
brands.forEach(brand => {
brand.models.map(model => {
this.vehicleLists.push(this.vehicleListAdapter.adapt(model));
});
});
});
}
,它现在将拥有所有品牌(带有嵌套模型)和您正在调整的模型。这由您决定最终数据的外观。