我正在尝试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
类?
谢谢!
答案 0 :(得分:39)
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);
}
答案 1 :(得分:26)
这是我的工作解决方案:
if (this._heroes != null && this._heroes !== undefined) {
return Observable.create(observer => {
observer.next(this._heroes);
observer.complete();
});
}
我希望这是最好的解决方案。