Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angular – ngIf容器打破异步ngFor大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在使用NgFor创建的列表周围包装ngIf容器时,我在Angular2中遇到了一些意外的行为.在NgIf容器变​​为可见之后,第一次插入时,视图似乎不会在可观察数组中呈现项目.

请参阅演示此意外行为的plunker demo.我期待第一个例子在Loaded出现的同时@L_262_2@香蕉.

做了一些愚蠢的事情还是这个渲染错误

Plunker demo

app.service.ts

export class Appservice {
  private _things = new Subject<Array<any>>();
    public things = this._things.asObservable();

  constructor() {
    var that = this;

    // simulate ajax request
    setTimeout(function() {
      that._things.next([
          {'id': 1,'text': 'banana'}
        ]);
    },3000);

    setTimeout(function() {
      that._things.next([
        {'id': 1,'text': 'banana'},{'id': 2,'text': 'orange'}
      ]);
    },6000);

    setTimeout(function() {
      that._things.next([
        {'id': 1,'text': 'orange'},{'id': 3,'text': 'apple'}
      ]);
    },9000);
  }
}

app.ts

@Component({
  SELEctor: 'my-app',template: `
    <h4>Does have *ngIf</h4>
    <div *ngIf="hasThings">
      Loaded
      <ul>
        <li *ngFor="let thing of things | async">
          {{thing.iD}}: {{thing.text}}
        </li>
      </ul>
    </div>

    <h4>Doesn't have *ngIf</h4>
    <div>
      Loaded
      <ul>
        <li *ngFor="let thing of things | async">
          {{thing.iD}}: {{thing.text}}
        </li>
      </ul>
    </div>
  `,directives: [NgClass,NgStyle,CORE_DIRECTIVES,FORM_DIRECTIVES]
})
export class App implements OnInit {
  public hasThings = false;

  private _things = new Subject<Array<any>>();
  public things = this._things.asObservable();

  constructor(private _appservice: AppservicE) {
  }

  ngOnInit() {
    this._appservice.things
      .subscribe(things => {
        this.hasThings = things.length > 0;
        this._things.next(things);
      });
  }
}

解决方法

原因是您在模板中使用COR_224_11845@ponent和异步管道中的Subject.如果将Component中的Subject对象更改为BehaviorSubject,您将获得预期的结果.

private _things = new BehaviorSubject<Array<any>>();

Subject和BehaviorSubject之间的主要区别之一是BehaviorSubject返回它在订阅时保留的最后一个值,当Subject没有时.在您的代码中,当满足第一个ngIf条件时,启动DOM并且第一个列表调用subscribe.那时,Subject不会发出任何东西,你必须等到下一个事件才能更新列表.

工作plnkr:https://plnkr.co/edit/Obso0Odl3PoPw699AQ5W?p=preview

大佬总结

以上是大佬教程为你收集整理的angular – ngIf容器打破异步ngFor全部内容,希望文章能够帮你解决angular – ngIf容器打破异步ngFor所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。