Angular 4 带有新 Observable 和 ng-template 的异步管道不起作用

Angular 4 Async pipe with new Observable and ng-template doesn't work

我正在尝试使用 Angular 4 异步管道和使用 new Observable() 创建的 Observable 来显示房间列表。

我有一个这样定义的 RoomService:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { DatabaseService } from '../core/database.service';
import { Room } from './room';

@Injectable()
export class RoomService {
  private store: any;

  constructor(private db: DatabaseService) {
    this.store = this.db.store('rooms');
  }

  getRooms(query: any = {}): Observable<Room[]> {
    return new Observable(observer => {
      this.store.find(query, (error, results) => {
        if (error) {
          observer.error(error);
        } else {
          const rooms = results.map(room => {
            return new Room(room.building, room.number, room._id);
          });
          observer.next(rooms);
        }
        observer.complete();
      });
   });
  }
}

和一个 RoomListComponent 定义如下:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { Room } from '../room';
import { RoomService } from '../room.service';

@Component({
  selector: 'app-room-list',
  templateUrl: './room-list.component.html',
  styleUrls: ['./room-list.component.scss']
})
export class RoomListComponent implements OnInit {
  rooms$: Observable<Room[]>;

  constructor(private roomService: RoomService) {}

  ngOnInit() {
    this.rooms$ = this.roomService.getRooms();
  }
}

我正在尝试像这样显示房间:

<h1>Rooms</h1>
<div *ngIf="$rooms | async as rooms; else loading">
  <div *ngFor="let room of rooms">
    {{ room.number }}
  </div>
</div>
<ng-template #loading>Loading...</ng-template>

但它不起作用。视图一直显示正在加载...谁能告诉我我的代码有什么问题吗?

不要在模板中调用方法,因为它会在每次更改检测时返回新的可观察对象。

你可以试试这个:

rooms$: Observable<Room[]>;

constructor(private roomService: RoomService) {}

ngOnInit() {
  this.rooms$ = this.roomService.getRooms()
}

view.html

<div *ngIf="rooms$ | async as rooms; else loading">

Plunker Example