我正在尝试 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')...
}
有没有办法做到这一点?
我怎样才能导入Observable
我的 ts 文件中的类?
Thanks!
TypeScript(或 JavaScript)中的方法被称为of http://reactivex.io/rxjs/class/es6/Observable.js%7EObservable.html#static-method-of. 学习 rxjs 也有一个很好的教程 https://www.learnrxjs.io/learn-rxjs/operators/creation/of
如果您正在使用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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)