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)
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)
我希望这是最好的解决方案.
| 归档时间: |
|
| 查看次数: |
35143 次 |
| 最近记录: |