Angular | 已知字典表value值,反显对应label

应用场景
在一些业务场景中,尤其是表单展示数据时,会包含一些存为字典表的数据,比如地址信息等,后端接口如果只返回了key值,则需要前端通过调用字典表接口去查询value值来反显到表单上。

业务html: dictSrv.province$是字段对应的字典表接口,返回值为ObservabledictTrans是字典转换管道(Pipe);province是后端传回的key取值;valuelabel的传值具体根据字典表返回的key和value对应的字段

<div>省份: {{ dictSrv.province$ | async | dictTrans: province	: 'value' : 'label' }}div>

字典转换Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'dictTrans',
})
export class DictTransPipe implements PipeTransform {
  // arr是取到的字典list
  transform(arr: any[], value, findKey, showKey?, equal: boolean = true): any {
    if (Array.isArray(arr) && value) {
      const data = arr.find(item => {
        if (equal) {
          return item[findKey] === value;
        } else {
          return value.includes(item[findKey]);
        }
      });
      return showKey ? (data ? data[showKey] : data) : data;
    }
    return value;
  }
}

你可能感兴趣的:(Angular,最佳实践)