从结果创建 Observable<T>

create Observable<T> from result

我正在尝试 Angular2。

我注意到 http 服务使用 Observable 对象而不是 Promise(我不太喜欢那个选择.. async/await 即将到来) .

在我的服务中,我从网络服务下载了一个 Plants 的列表。单击一个工厂,我会使用路由显示详细信息。 但是这样我回去的时候又重新下载了植物(因为又调用了构造函数)

为了避免这种情况,我想做类似的事情:

public getPlants(): Observable<Plants[]>
{   
    if (this._plants != null)
        return Observable.fromResult (this._plants); //This method does not exists 

    return this._http.get('../../res/heroes.json')...
}

有办法吗? 如何在我的 ts 文件中导入 Observable class?

谢谢!

这是我的工作解决方案:

if (this._heroes != null && this._heroes !== undefined) {
    return Observable.create(observer => {
        observer.next(this._heroes);
        observer.complete();
    });
}

我希望这是最好的解决方案。

TypeScript 中的方法(或 JavaScript 就此而言)被称为 of. Learn rxjs has a nice tutorial as well

如果您正在使用 rxjs6,您可以从 rxjs

获得所有内容
import { Observable, of } from 'rxjs';

public getPlants(): Observable<Plant[]> {
  const mocked: Plant[] = [
    { id: 1, image: 'hello.png' }
  ];
  // returns an Observable that emits one value, mocked; which in this case is an array,
  // and then a complete notification
  // You can easily just add more arguments to emit a list of values instead
  return of(mocked);
}

在以前的版本中,您从不同的位置导入了运算符

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

public getPlants(): Observable<Plant[]> {
  const mocked: Plant[] = [
    { id: 1, image: 'hello.png' }
  ];
  return of(mocked);
}

在此之前,您将其导入为 Observable 的扩展 class

import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/of';

public getPlants(): Observable<Plants[]> {
    // this can be changed to a member variable of course
    let mocked: Plants[] = [{
        id: 1,
        image: "hello.png"
    }];
    return Observable.of(mocked);
}