组件初始化之前的Angular Load Async数据

时间:2018-08-02 09:06:18

标签: javascript angular asynchronous service angular-resolver

使用API​​调用中的数据时遇到问题:我想使用检索到的数据来设置复选框中的选中状态,但是在api响应之前初始化了该组件,并且出现了一些控制台错误:

  

错误TypeError:无法读取未定义的属性'id'

我也使用解析器测试了行为,但是即使在初始化之前就记录了响应数组,我也遇到了同样的问题:

component.ts

...
export class RolesComponent implements OnInit {

  flag: boolean = false;
  simpleArr: object[] = [
    { userId: 1, id: 2 },
    { userId: 1, id: 3 },
    { userId: 1, id: 5 },
    { userId: 1, id: 7 }
  ]
  permArr: object[] = [];
  permArrResolved: object[] = [];

  levels = [
    { name: 0, description: 'Creazione nuovo utente' },
    { name: 1, description: 'Reset password di qualsiasi utente' },
    { name: 2, description: 'Eliminazione di qualsiasi utente' },
    { name: 3, description: 'Modifica livello di qualsiasi utente' },
    { name: 4, description: 'Rinnovo delle licenze' },
    { name: 5, description: 'Gestione completa delle licenze' },
    { name: 6, description: 'Gestione completa dei clienti' },
    { name: 7, description: 'Gestione completa dei PC' }
  ];

  constructor(private api: RolesApiService, private route: ActivatedRoute, ) {

    this.api.getKeys().subscribe(keys => {
      this.permArr = keys;
      console.log(this.permArr);
      this.flag = true
    });

    this.route.data.pipe(
      map(data => data.cres)).subscribe((key) => {
        this.permArrResolved = key;
        console.log(this.permArrResolved);
      });

  }

  ngOnInit() {
    console.log('component is initialized');
  }

}

component.html

<form *ngIf="flag">
  <h2>with permArr[0].id</h2>
  <ng-container *ngFor="let level of levels">
    <input type="checkbox" [checked]="level.name === permArr[0]?.id" />{{level.name}} - {{level.description}}
    <br>
  </ng-container>

<hr>

<h2>with simpleArr[level.name].id</h2>
  <ng-container *ngFor="let level of levels">
    <input type="checkbox" [checked]="level.name === simpleArr[level.name]?.id" />{{level.name}} - {{level.description}}
    <br>
  </ng-container>

<hr>

  <h2>with permArr[level.name].id</h2>
  <ng-container *ngFor="let level of levels">
    <input type="checkbox" [checked]="level.name == permArr[level.name]?.id" />{{level.name}} - {{level.description}}
    <br>
  </ng-container>

<hr>

  <h2>with permArr[level.name].id using resolver</h2>
  <ng-container *ngFor="let level of levels">
    <input type="checkbox" [checked]="level.name == permArrResolved[level.name]?.id" />{{level.name}} - {{level.description}}
    <br>
  </ng-container>

</form>

我进行了stackblitz演示,以显示错误,api服务,路由和我使用的解析器。在这里:https://stackblitz.com/edit/async-angular-resolver

我该如何解决这个问题?

编辑:使用安全的运算符不能解决该错误 EDIT2:在表单标签中使用* ngIf不能解决该错误

4 个答案:

答案 0 :(得分:3)

这里已经有几个答案可以正确回答您要问的问题-它们对您不起作用的原因是因为您绑定的数据与您的ID不匹配。

您之前的问题基本上都是在问同一件事:

为避免社区进一步浪费您的精力,我已着手编写您应该自己编写的调试代码。正如一些人已经建议的那样,这表明安全导航操作员是如何解决模板问题的-用*ngIf换行也可以解决问题,而我添加的值说明了为什么您的复选框未选中。

https://stackblitz.com/edit/async-angular-resolver-hxxyw4?file=src/app/roles/roles.component.html

答案 1 :(得分:2)

您可以使用safe navigation operator?.

  

Angular安全导航运算符(?。)是防止属性路径中的空值和未定义值的一种流畅便捷的方法。

例如:

[checked]="level.name === permArr[0]?.id"

这基本上等于permArr[0] && permArr[0].id

答案 2 :(得分:1)

使用*ngIf响应后加载视图:

<form *ngIf="flagpermArr && flagpermpermArrResolved">
    <h2>with permArr[0].id</h2>

    <ng-container *ngFor="let level of levels">
        <input type="checkbox" [checked]="level.name === permArr[0]?.id" />{{level.name}} - {{level.description}}
        <br>
    </ng-container>
    <hr>
    <h2>with simpleArr[level.name].id</h2>

    <ng-container *ngFor="let level of levels ; let i = index">

 <!-- <input *ngIf="" type="checkbox" [checked]="level.name === simpleArr[level.name].id" />{{level.name}} - {{level.description}} 
    -->
        <br>
    </ng-container> 
    <hr>
    <h2>with permArr[level.name].id</h2>
    <ng-container *ngFor="let level of levels">
        <input type="checkbox" [checked]="level.name == permArr[level.name]?.id" />{{level.name}} - {{level.description}}
        <br>
    </ng-container>
    <hr>
    <h2>with permArr[level.name].id using resolver</h2>
    <ng-container *ngFor="let level of levels">
        <input type="checkbox" [checked]="level.name == permArrResolved[level.name]?.id" />{{level.name}} - {{level.description}}
        <br>
    </ng-container>
</form>

TS:

 export class RolesComponent implements OnInit {

  flagpermArr: boolean = false;
  flagpermpermArrResolved: boolean = false;

  simpleArr: object[] = [
    { userId: 1, id: 1 },
    { userId: 1, id: 2 },
    { userId: 1, id: 5 },
    { userId: 1, id: 7 }
  ]
  permArr: object[] = [];
  permArrResolved: object[] = [];

  levels = [
    { name: 0, description: 'Creazione nuovo utente' },
    { name: 1, description: 'Reset password di qualsiasi utente' },
    { name: 2, description: 'Eliminazione di qualsiasi utente' },
    { name: 3, description: 'Modifica livello di qualsiasi utente' },
    { name: 4, description: 'Rinnovo delle licenze' },
    { name: 5, description: 'Gestione completa delle licenze' },
    { name: 6, description: 'Gestione completa dei clienti' },
    { name: 7, description: 'Gestione completa dei PC' }
  ];

  constructor(private api: RolesApiService, private route: ActivatedRoute, ) {
  }

  ngOnInit() {
    this.api.getKeys().subscribe(keys => {
      this.permArr = keys;
      this.flagpermArr = true
    });

    this.route.data.pipe(
      map(data => data.cres)).subscribe((key) => {
        this.permArrResolved = key;
        this.flagpermpermArrResolved = true
      });
  }

答案 3 :(得分:0)

您可以使用:

<ng-container *ngIf="permArr && permArrResolved"> your code here </ng-container>

仅当permArr和perArrResoved中包含数据时,才会显示容器内容。