Angular 管道:将字符串转换为 Json 并获取成员值

Angular Pipe: Convert string into Json and get member value

是否有一个 Angular 管道接受字符串文本,并让用户获得实际值?

String: {"ProductId": "1234", "ProductName": "Computer"}

预期管道:

(item | pipe).productName 
===> results in 'Computer'

(item | pipe).productId
===> results in 1234

资源:

下面的管道将对象转换为 json。 https://angular.io/api/common/JsonPipe

我需要转换字符串,并得到一个成员值

我没见过像你说的那样的烟斗,但如果你自己做的话可能是这样的……:

创建了这个并对其进行了测试...使用您提供的描述数据效果非常好。

@Pipe({
  name: 'jsonParse'
})
export class JsonParsePipe implements PipeTransform {

  transform(value: string, ...args: unknown[]): any {
    return JSON.parse(value);
  }

}

在其中一个组件中,我将其定义为组件的成员 class:

  data = JSON.stringify({ ProductId: '1234', ProductName: 'Computer' });

并且 HTML 是这样的:

<div>{{ (data| jsonParse).ProductId }}</div>

我很确定你可以通过一些重载来增加它的趣味性,为它提供更多功能以供将来使用...

您可以制作一个像 Ashwyn 一样的自定义管道,或者只在您的组件中制作一个函数来执行相同的操作

Stackblitz

Component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  str = '{"ProductId": "1234", "ProductName": "Computer"}';

  parseJson(str: string): any {
    return JSON.parse(str);
  }
}

Template.Html

<div>{{parseJson(str).ProductName}}</div>

我会说,如果您认为您需要在整个应用程序中使用类似的功能,那就制作一个管道。如果这是一次性的事情,只需在组件内创建一个函数即可。

这也适用:

打字稿:

export class ToJsonPipe implements PipeTransform {
  transform(value: string): any {
    try {
      return JSON.parse(value);
    } catch {
      return null;
    }
  }
}

HTML:

{{ (item?.request | toJson)?.ProductName }}