angular - 在具有异步数据的 ng2 智能表中使用管道
问题描述
我尝试使用管道,但在我的管道中有异步数据:我的管道:
import { Pipe, PipeTransform } from "@angular/core";
import { VehiculeService } from "app/pages/fleetManagement/services/vehicule.service";
import { map } from "rxjs/operators";
@Pipe({
name: "convertVehicule"
})
export class ConvertVehiculePipe implements PipeTransform {
public result: any;
constructor(private vehicleService: VehiculeService) {}
transform(value) {
this.vehicleService
.getVehicules()
.pipe(
map((data: any = []) => {
let result;
for (let j = 0; j < data.length; j++) {
if (value === data[j].id) {
result = data[j].registration_number;
}
}
return result;
})
)
.subscribe(
(data: any = []) => {
console.log(data);
this.result = data;
}, // },
error => {
console.log(error);
}
);
console.log(this.result);
return this.result;
}
}
}
在我的组件中:
this.settings = { ...,
vehicule_fleet_id: {
title:"vehicle id",
type: "html",
editor: {
type: "custom",
component: SelectAssuranceComponent
},
valuePrepareFunction: cell => {
let formated = this.convertVehiclePipe.transform(cell);
return formated;
}
}
}
我这样做了,但是 console.log(this.result) 是未定义的,我不知道问题是不是时间问题,因为 valuePrepareFunction 是直接渲染的,还是问题出在管道函数中,正是订阅内的变量范围可观察的和订阅之外的
解决方案
我找到了解决方案,显然我们不能在管道内使用服务,所以我只是从管道中删除了服务并在组件中调用它:在我的管道中:
transform(value, data) {
let result;
console.log(value);
console.log(data);
for (let j = 0; j < data.length; j++) {
if (value === data[j].id) {
result = data[j].registration_number;
console.log(result);
}
}
console.log(result);
return result;
}
在 ngOninit 中:
ngOnInit(): void {
this.vehiculeService.getVehicules().subscribe(data => {
this.vehicleData = data;
})
};
在 valuePrepareFunction 中:
valuePrepareFunction: cell => {
console.log(cell);
let formated = this.convertVehiclePipe.transform(
cell,
this.vehicleData
);
console.log(formated);
return formated;
}
它工作得很好,我希望它能帮助别人
推荐阅读
- reactjs - 如何在 echarts 热图单元格上添加点击事件?
- r - 从单独的列表中添加具有适当值的新列
- scala - 为什么scala无法解析T参数
- java - Swagger 描述在 Spring Boot 应用程序中隐藏端点
- kubernetes - 安排一个 Kubernetes cronjob 只运行一次
- javascript - 如何处理 node.js 中的 json-parse 错误
- ios - largeTitleDisplayMode SwiftUI 中的字母间距
- java - 添加反应导航6.x后无法使用yarn android
- xamarin.forms - 具有最小限制的按钮计数
- r - 通过在 R 中使用列表的组计算平均值