访问从 Angular 中的组件传递的对象

Accessing object passed from component in Angular

我有以下 class 名为 Enumeration:

export class Enumeration {
    name: string;
    values: Object;
}

现在在我的组件中,我已经创建了我的对象并填充了数据。

在他的模板中我有这样的东西:

<div class="card-item-content">
  <span>{{enumeration | json}}</span>
</div>

这正常工作,我可以看到:

{ "name": "employee-type", "values": [ null, { "id": 1, "text": "Employee" }, { "id": 2, "text": "Contractor" }, { "id": 3, "text": "Newjoiner" }, null, { "id": 5, "text": "Consultant" }, { "id": 6, "text": "GCP" }, { "id": 7, "text": "Career Counselor" } ] }

但是当我尝试

{{enumeration.name | json}} or {{enumeration.values | json}}

我收到此错误消息:

Cannot read property 'name' of undefined

当我这样做时:

*ngFor="let enum of enumeration.values"

它将循环 8 次,但第一个跨度为空,然后循环 3 次

[object Object] 

然后是另一个空跨度,然后是之前的 3 倍。

关键是我想访问 values 对象 属性 中的每个 not 空对象,属性ies textid.

所以结果应该是 6 个具有以下内容的跨度:

Employee 1
Contractor 2
Newjoiner 3
Consultant 5
GCP 6
Career Counselor 7

有人可以给我一些提示吗?

更新 - 已解决

所以我只在模板中这样做了。

<ng-container *ngFor="let enum of enumeration?.values">
   <span *ngIf="enum">{{enum?.text}} : {{enum?.id}}</option>
</ng-container>

这是我的 ngOnInit:

 ngOnInit() {
    if (this.id != null) {
      const enumName = employeeDetailsEnumMapping.get(this.id);
      this.enumsService.getEnums().subscribe(data => {
        this.enumeration = data.get(enumName);
        if (this.enumeration == null) {
          console.error(`missing enum ${this.id}`);
        }
      });
    }
  }

当我添加时:

this.enumeration.values = this.enumeration.values.filter(x => x != null);

它说:

'filter' property does not exist on type 'Object';

帮我解决了这个问题。但我想实际上过滤方式会更好看。

{{(enumeration | json)?.name}}

首先得到json,然后尝试进入一个变量。有用吗?

json 对象应该用 {}[] 括起来。

{{enumeration.name | json}} or {{enumeration.values | json}}

不是有效的 json,因此结果为 undefined

我猜你想要的是从数组中删除所有 null 值,这样你就可以正确访问数组中的对象,所以你可以在你的订阅中这样做:

.subscribe(data => {
  this.enumeration = data;
  this.enumeration.values = this.enumeration.values.filter(x => x != null);        
})

那么您的迭代应该可以正常工作,使用安全导航运算符来保护 null 值(如果这是异步的)

<div *ngFor="let enum of enumeration?.values">
  {{enum.text}}
</div>

Demo