angular – ngIf容器打破异步ngFor

前端之家收集整理的这篇文章主要介绍了angular – ngIf容器打破异步ngFor前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在使用ngFor创建的列表周围包装ngIf容器时,我在Angular2中遇到了一些意外的行为.在ngIf容器变​​为可见之后,第一次插入时,视图似乎不会在可观察数组中呈现项目.

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

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

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);
      });
  }
}

解决方法

原因是您在模板中使用Component和异步管道中的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

猜你在找的Angularjs相关文章