从结果创建Observable <T>

use*_*528 30 observable rxjs typescript angular

我正在尝试Angular2.

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

在我的服务中,我Plants从webservice 下载了一个列表.单击工厂我使用路由显示详细信息.但是当我回去的时候,再次下载植物(因为再次调用构造函数).

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

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')...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?如何Observable在ts文件中导入该类?

谢谢!

Pat*_*ick 45

调用TypeScript(或JavaScript中的方法)中的方法of.学习rxjs也有一个很好的教程

如果您使用的是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);
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

在此之前,您将其作为Observable类的扩展名导入

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我发现我还需要添加`import'rxjs/add/observable/of';`. (2认同)
  • 如果您不想逐个添加所有运算符,也可以从'rxjs/Rx'`导入. (2认同)

use*_*528 26

这是我的工作解决方案:

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

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

  • 什么是变量/参数“观察者”的类型? (2认同)
  • 这是[订阅者](https://github.com/ReactiveX/rxjs/blob/master/src/Subscriber.ts).参见[Observable.create()](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-create)和[new Observable()](http:// reactivex .io/rxjs/class/es6/Observable.js~Observable.html#instance-constructor-constructor)文档. (2认同)
  • 我认为这是较旧的,但我仍然想保持更新,Observable.create() 已弃用并建议使用新的 Observable()。并且 of() 也不再在 rxjs 中或已弃用。还是我忽略了? (2认同)