angular - 管道服务角度的异步功能
问题描述
我需要从 Angular 中查找省份名称,所以我编写了一个管道服务来查找带有代码的名称这是我的代码管道
export class ConvertStatePipe implements PipeTransform {
constructor(private callData: CallDataService) {}
transform(value: string): any {
let nameProvince = '';
this.callData.getAllProvinces().subscribe( (res) => {
for (const item of res.provinces) {
if (item.provinceCode === value) {
nameProvince = item.name;
}
}
});
return nameProvince;
}
在这里,我从 CallDataService 调用了 CallDataService 我有一个名为 getAllProvinces 的函数,我现在从我设置的 API 中获取所有省份,因为我需要从 HTML 中找到省份名称并返回名称,这是我的 HTML 代码
<div class="mb-24 terminal-item" fxFlex="33.33333%">
<strong>Province</strong>
{{userData.state | convertState }}
</div>
但我不能 retunr 变量 nameProvince 因为这个未定义,我认为因为 this.callData.getAllProvinces() 不是异步的,你知道吗?
解决方案
- 从你的管道返回一个可观察的
- 将异步管道与您的管道一起使用,它将为您解析订阅
-- 尝试如下更新:
{{userData.state | async | convertState }}
// 在你的管道中
export class ConvertStatePipe implements PipeTransform {
constructor(private callData: CallDataService) {}
transform(value: string): any {
let nameProvince = '';
// update below to return observable
nameProvince = this.callData.getAllProvinces().pipe( map((res) => {
let value = '';
for (const item of res.provinces) {
if (item.provinceCode === value) {
value = item.name;
}
}
return value;
}));
return nameProvince;
}
- 不要订阅管道转换,只需使用rxjs 管道和 map 运算符进行过滤,它将返回一个可观察的 rest 异步管道将负责解决它。
推荐阅读
- ios - 使用 UICollectionViewCompositionalLayout 水平滚动多个部分
- react-native - 遵循说明后面料问题应用程序未显示
- c# - 报表查看器导出按钮再次加载数据
- node.js - 为什么我的 express-validator 没有检测到函数?
- ansible - 需要仅使用索引号从第一个寄存器变量引用到第二个变量
- sass - SCSS 级父级
- maven - Spring Boot 应用程序未启动 tomcat
- amazon-cloudformation - 如何使用 Cloudformation 模板中的变量作为 terraform 中“数据源”的功能
- c# - vs2019社区版每次修改代码都必须手动重新生成,否则不起作用
- cakephp - 自定义 cakephp ConsoleLog 消息