Return an empty Observable

前端 未结 11 1028
北荒
北荒 2020-11-30 18:23

The function more() is supposed to return an Observable from a get request

export class Collection{

    public more = (): Observab         


        
相关标签:
11条回答
  • 2020-11-30 18:49

    RxJS 6

    you can use also from function like below:

    return from<string>([""]);
    

    after import:

    import {from} from 'rxjs';
    
    0 讨论(0)
  • 2020-11-30 18:50

    Or you can try ignoreElements() as well

    0 讨论(0)
  • 2020-11-30 18:57

    With the new syntax of RxJS 5.5+, this becomes as the following:

    // RxJS 6
    import { EMPTY, empty, of } from "rxjs";
    
    // rxjs 5.5+ (<6)
    import { empty } from "rxjs/observable/empty";
    import { of } from "rxjs/observable/of";
    
    empty(); // deprecated use EMPTY
    EMPTY;
    of({});
    

    Just one thing to keep in mind, EMPTY completes the observable, so it won't trigger next in your stream, but only completes. So if you have, for instance, tap, they might not get trigger as you wish (see an example below).

    Whereas of({}) creates an Observable and emits next with a value of {} and then it completes the Observable.

    E.g.:

    EMPTY.pipe(
        tap(() => console.warn("i will not reach here, as i am complete"))
    ).subscribe();
    
    of({}).pipe(
        tap(() => console.warn("i will reach here and complete"))
    ).subscribe();
    
    0 讨论(0)
  • 2020-11-30 18:57

    In my case with Angular2 and rxjs, it worked with:

    import {EmptyObservable} from 'rxjs/observable/EmptyObservable';
    ...
    return new EmptyObservable();
    ...
    
    0 讨论(0)
  • 2020-11-30 18:59

    Several ways to create an Empty Observable:

    They just differ on how you are going to use it further (what events it will emit after: next, complete or do nothing) e.g.:

    • Observable.never() - emits no events and never ends.
    • Observable.empty() - emits only complete.
    • Observable.of({}) - emits both next and complete (Empty object literal passed as an example).

    Use it on your exact needs)

    0 讨论(0)
  • 2020-11-30 19:01

    Came here with a similar question, the above didn't work for me in: "rxjs": "^6.0.0", in order to generate an observable that emits no data I needed to do:

    import {Observable,empty} from 'rxjs';
    class ActivatedRouteStub {
      params: Observable<any> = empty();
    }
    
    0 讨论(0)
提交回复
热议问题