angular2如何使用复杂的observable而无需重复订阅

时间:2016-02-15 21:45:41

标签: angular observable

我有一个类Page(下面的定义)和返回可观察页面的服务。如何在没有重复订阅的情况下正确使用observable。 Plunker(不工作)http://plnkr.co/edit/8xwclHsGm2jKdW9A0fZ4?p=preview

export class Page<T>{
  content: Array<T> = new Array();
  last: boolean = true;
  totalPages: number = 0;
  totalElements: number = 0;
  size: number = 0;
  number: number = 0; // Page number
  first: boolean = true;
  numberOfElements: number = 0; //Number of elements in current page
}


export class DataGridService {
  getPageForGrid(gridName:string):Observable<Page<any>>{
    return anObservable; //code removed. see plunker
  }
}


@Component({
    selector: 'data-grid',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `<div class="row">
  <ul>
    <li>Page size: {{page.size}}</li>
    <li>Number: {{page.number}}</li>
    <li>Total pages: {{page.totalPages</li>
    <li>Total Elements: {{page.totalElements}}</li>
    <li>Number of elements:{{page.numberOfElements}}</li>
  </ul>
  <div>
    <table>
      <tbody>
        <tr *ngFor="#row of page.content; #i = index">
          <td>{{row['column1']}}</td>
          <td>{{row['column2']}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>`,
providers:[DataGridService]
})
export class DataGridComponent {
  @Input gridName: string;

  page: Observable<Page<any>>;

  constructor(){
    this.dataGridService = new DataGridService();
  }

  ngOnChanges(changes){
    this.page = this.dataGridService.getPageForGrid(this.gridName);
  }
}

1 个答案:

答案 0 :(得分:0)

我对您的代码进行了一些更改,您可以看到working plunker here

正如您在此处所看到的,Observable根本不复杂,并且它并不关心它发出的数据类型。它可以是简单的字符串,数据对象(就像你的情况一样)或其他任何东西。

我建议您使用Observable作为生成器,就像我使用Observable.of()一样,并且不要使用new Observable(),至少在您真正理解之前它是如何工作的......

@Injectable()
export class DataGridService {
  getPageForGrid(gridName:string):Observable<Page<any>>{
  var page = new Page();
      page.size = 2;
      page.totalPages = 10;
      page.totalElements=19;
      page.numberOfElements=2;
      page.content = [{column1:"11", column2:"12"},{column1:"21", column2:"22"}];

    return Observable.of(page));
  }
}

@Component(...)
export class DataGridComponent {
  constructor(public dataGridService: DataGridService){
    this.dataGridService.getPageForGrid(this.gridName)
      .subscribe(page => this.page = page);
  }
}