【问题标题】:async function from pipe service angular管道服务角度的异步功能
【发布时间】:2020-07-01 16:17:31
【问题描述】:

我需要从角度查找省份名称,所以我编写了一个管道服务来查找名称,代码这是我的代码管道

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>

但我无法返回变量 nameProvince,因为这个未定义,我认为因为 this.callData.getAllProvinces() 不是异步的,你知道吗?

【问题讨论】:

标签: angular typescript pipe frontend angular-pipe


【解决方案1】:
  1. 从你的管道中返回一个 observable
  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 管道和映射操作符 进行过滤,它会返回一个可观察的 rest 异步管道会小心解决它。

【讨论】:

  • @nima amr:上面的逻辑是不是对你不起作用?你得到什么错误?
猜你喜欢
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2021-01-11
  • 1970-01-01
  • 2019-04-10
  • 2021-02-02
  • 2016-09-05
相关资源
最近更新 更多