Javascript 发出单个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34893822/
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 17:00:31  来源:igfitidea点击:

Emit a single value

javascriptangularrxjs

提问by pixelbits

I would like to emit a single value.

我想发出一个值。

According to this post, the following should be valid:

根据这篇文章,以下内容应该是有效的:

var requestStream = Rx.Observable.just('https://api.github.com/users');

However, this does not work. justis not defined.

但是,这不起作用。just没有定义。

Has it been deprecated? Is there something that I can use instead?

它被弃用了吗?有什么可以代替的吗?

回答by Mark Meyer

A lot of the stuff is tucked away in: import 'rxjs/Rx';You might try Observable.offor a single value.

很多东西都藏在里面: import 'rxjs/Rx';你可能会尝试Observable.of一个单一的价值。

This works for me (plunker):

这对我有用plunker):

import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{test | async}}</h2>     
    </div>
  `,
  directives: []
})
export class App {
    test: Observable<any> = Observable.of("I'm an observable");
    constructor() {
  }
}

回答by user3743222

.just(value)is from RxJS v4 while angular2 is using the v5. It has gone through an extensive rewrite, and it is still in beta so operators are missing/changed names in v5.

.just(value)来自 RxJS v4,而 angular2 使用的是 v5。它经过了广泛的重写,但仍处于测试阶段,因此 v5 中的操作符缺少/更改了名称。

.ofis just fine, as MarkM mentioned. I just wanted to add that you can also use .fromwhich works if you have just one value, or an array of values. To reuse the example from your accepted answer, you would use something like (plunkr):

.of就好了,正如 MarkM 提到的那样。我只是想补充一点.from,如果您只有一个值或一组值,您也可以使用which 。要重用您接受的答案中的示例,您可以使用类似 ( plunkr) 的内容:

//our root app component
import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{test | async}}</h2>

    </div>
  `,
  directives: []
})
export class App {
    test: Observable<any> = Observable.from(["I'm an observable"]);
    constructor() {
  }
}

回答by Finesse

Use the offunction:

使用of函数:

import {of} from 'rxjs';

var requestStream = of('https://api.github.com/users');