创建Observable< T>从结果 [英] create Observable<T> from result

查看:62
本文介绍了创建Observable< T>从结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Angular2.

I am trying Angular2.

我注意到http服务使用Observable对象而不是Promise(我不太喜欢这个选择..async/await即将到来).

I noticed that the http service use Observable object instead of Promise (I don't like much that choice.. async/await are arriving).

在我的服务中,我从Web服务下载了Plants的列表.单击一个工厂,我将使用工艺路线显示详细信息. 但是以这种方式,当我返回时,再次下载了植物(因为再次调用了构造函数).

In my service, I download a list of Plants from the webservice. Clicking on a plant I show the details using the routing. But in this way when I go back, the plants are downloaded again (because the constructor is called again).

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

To avoid this I want to do something like:

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类?

Is there a way to do that? How can I import the Observable class in my ts file?

谢谢!

推荐答案

TypeScript(或JavaScript)中的方法称为了解rxjs也有不错的教程

The method in TypeScript (or JavaScript for that matter) is called of. Learn rxjs has a nice tutorial as well

如果您使用的是 rxjs6 ,则可以从rxjs

If you are using rxjs6 you get everything from 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);
}


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


In previous version you imported the operator of from a different location

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类的扩展


And before that you imported it as an extension for the Observable class

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);
}

这篇关于创建Observable&lt; T&gt;从结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆