首页 > 解决方案 > 管道服务角度的异步功能

问题描述

我需要从 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() 不是异步的,你知道吗?

标签: angulartypescriptpipefrontendangular-pipe

解决方案


  1. 从你的管道返回一个可观察的
  2. 异步管道与您的管道一起使用,它将为您解析订阅

-- 尝试如下更新:

   {{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 异步管道将负责解决它。

推荐阅读