小编Ign*_*asi的帖子

以编程方式使用 AsyncPipe - Angular 2

我正在使用一个组件来像数据一样呈现表格,我给它列的列表、数据、数据如何映射到每列,最后是一个应用于每列数据的管道列表。

到目前为止一切顺利,唯一的问题是当这些管道之一是异步管道时......

经过一段时间的试验,我发现在模板上使用 asyncpipe 时,transform 方法会被多次调用。但是,如果我以编程方式使用它,转换方法只会被调用一次(我调用它的时间)。

我猜它在模板上被多次调用的原因是因为它是一个不纯的管道,但我该如何以编程方式处理它?

这是一个plunker展示了我刚才所说的内容:

@Injectable()
export class AsyncProvider {
  constructor() {}
  
  getById(id: number) {
    // Just some mock data
    return Observable.of({id, times_five: id*5}).delay(1000);
  }
}

@Component({
  selector: 'my-app',
  providers: [AsyncPipe, AsyncProvider]
  template: `
    <div>
      <p>Template async pipe</p>
      <p>{{ asyncObj | async | json }}</p>
      <hr>
      <p>Programmatically async pipe</p>
      <p>{{ asyncObjPiped | json }}</p>
    </div>
  `,
  directives: []
})
export class App {
  constructor(
    private _provider: AsyncProvider,
    private _async: AsyncPipe
  ) {
    this.asyncObj = this._provider.getById(123); …
Run Code Online (Sandbox Code Playgroud)

angular-pipe angular

3
推荐指数
1
解决办法
1673
查看次数

标签 统计

angular ×1

angular-pipe ×1