我正在尝试 Angular2。
我注意到 http 服务使用 Observable
对象而不是 Promise
(我不太喜欢那个选择.. async
/await
正在到达)。
在我的服务中,我从网络服务下载了一个植物
列表。单击一个工厂,我会使用路由显示详细信息。
但是这样我回去的时候又重新下载了植物(因为又调用了构造函数)。
为了避免这种情况,我想做类似的事情:
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
类?
谢谢!
最佳答案
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 类的扩展导入
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);
}
关于typescript - 从结果创建 Observable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34660010/