create Observable from result

前端 未结 2 1867
滥情空心
滥情空心 2021-02-03 19:48

I am trying Angular2.

I noticed that the http service use Observable object instead of Promise (I don\'t like much that choice.. async

2条回答
  •  余生分开走
    2021-02-03 20:10

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

    If you are using rxjs6 you get everything from rxjs

    import { Observable, of } from 'rxjs';
    
    public getPlants(): Observable {
      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 {
      const mocked: Plant[] = [
        { id: 1, image: 'hello.png' }
      ];
      return of(mocked);
    }
    

    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 {
        // this can be changed to a member variable of course
        let mocked: Plants[] = [{
            id: 1,
            image: "hello.png"
        }];
        return Observable.of(mocked);
    }
    

提交回复
热议问题