Javascript 返回一个空的 Observable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38548407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:35:40  来源:igfitidea点击:

Return an empty Observable

javascripttypescriptrxjsobservable

提问by Murhaf Sousli

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

该函数more()应该Observable从获取请求中返回一个

export class Collection{

    public more = (): Observable<Response> => {
       if (this.hasMore()) {

         return this.fetch();
       }
       else{
         // return empty observable
       }
    }

    private fetch = (): Observable<Response> => {
       return this.http.get('some-url').map(
          (res) => {
              return res.json();
          }
       );
    }
}

In this case I can only do a request if hasMore()is true, else I get an error on subscribe()function subscribe is not defined, how can I return an empty observable?

在这种情况下,如果hasMore()为真,我只能做一个请求,否则我在subscribe()函数上得到一个错误subscribe is not defined,我怎样才能返回一个空的 observable?

this.collection.more().subscribe(
   (res) =>{
       console.log(res);
   },
   (err) =>{
       console.log(err);
   }
)

Update

更新

In RXJS 6

在 RXJS 6

import { EMPTY } from 'rxjs'

return EMPTY; 

采纳答案by Andrei Petrov

For typescript you can specify generic param of your empty observable like this:

对于打字稿,您可以像这样指定空 observable 的通用参数:

import 'rxjs/add/observable/empty' 

Observable.empty<Response>();

回答by Stephen Lautier

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

使用 RxJS 5.5+ 的新语法,这变成如下:

// RxJS 6
import { empty, of } from "rxjs";

// rxjs 5.5+ (<6)
import { empty } from "rxjs/observable/empty";
import { of } from "rxjs/observable/of";

empty();
of({});

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

要记住的一件事是empty()完成可观察的,因此它不会next在您的流中触发,而只会完成。因此,例如,如果您有 ,tap它们可能不会如您所愿地触发(请参见下面的示例)。

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

of({})创建 anObservable并发出值为 的 next{}然后它完成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();

回答by Simon_Weaver

RxJS6 (without compatibility package installed)

RxJS6(未安装兼容包)

There's now an EMPTYconstant and an emptyfunction.

现在有一个EMPTY常量和一个empty函数。

  import { Observable, empty, of } from 'rxjs';

  var delay = empty().pipe(delay(1000));     
  var delay2 = EMPTY.pipe(delay(1000));

Observable.empty()doesn't exist anymore.

Observable.empty()不存在了。

回答by Marcel Tinner

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

在我使用 Angular2 和 rxjs 的情况下,它适用于:

import {EmptyObservable} from 'rxjs/observable/EmptyObservable';
...
return new EmptyObservable();
...

回答by Toan Nguyen

Yes, there is am Emptyoperator

是的,有一个Empty运算符

Rx.Observable.empty();

For typescript, you can use from:

对于打字稿,您可以使用from

Rx.Observable<Response>.from([])

回答by Andrii Verbytskyi

Several ways to create an Empty Observable:

创建 Empty Observable 的几种方法:

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

它们只是在您将如何进一步使用它(它将在之后发出什么事件:nextcompletedo nothing)方面有所不同,例如:

  • Observable.never()- emits no events and never ends.
  • Observable.empty()- emits only complete.
  • Observable.of({})- emits both nextand complete(Empty object literal passed as an example).
  • Observable.never()- 不发出任何事件并且永不结束。
  • Observable.empty()- 只发出complete.
  • Observable.of({})- 发出nextcomplete(作为示例传递的空对象文字)。

Use it on your exact needs)

根据您的确切需求使用它)

回答by Chybie

You can return Observable.of(empty_variable), for example

例如,您可以返回 Observable.of(empty_variable)

Observable.of('');

// or
Observable.of({});

// etc

回答by Tuong Le

Or you can try ignoreElements()as well

或者你可以尝试ignoreElements()以及

回答by Callat

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:

带着类似的问题来到这里,上面的内容对我不起作用:"rxjs": "^6.0.0",为了生成一个不发出我需要做的数据的 observable:

import {Observable,empty} from 'rxjs';
class ActivatedRouteStub {
  params: Observable<any> = empty();
}

回答by Jorawar Singh

Try this

尝试这个

export class Collection{
public more (): Observable<Response> {
   if (this.hasMore()) {
     return this.fetch();
   }
   else{
     return this.returnEmpty(); 
   }            
  }
public returnEmpty(): any {
    let subscription = source.subscribe(
      function (x) {
       console.log('Next: %s', x);
    },
    function (err) {
       console.log('Error: %s', err);
    },
    function () {
       console.log('Completed');
    });
    }
  }
let source = Observable.empty();