问题描述
我很困惑如何导入这些运算符.有些我可以导入import 'rxjs/add/operator/do';
还有一些我不能.例如,这不起作用:import 'rxjs/add/operator/map';
(我检查了 rxjs/add/operator,map 存在于那里).
I am confused how to import those operators. Some I can import withimport 'rxjs/add/operator/do';
and some I can not. For ex, this does not work:import 'rxjs/add/operator/map';
(I checked in rxjs/add/operator, map exists there).
基本上我想做的是在 Angular4 中重现这个:
Essentially what I am trying to do is to reproduce this in Angular4:
var requestStream = Rx.Observable.just('https://api.github.com/users');
var responseStream = requestStream
.flatMap(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
responseStream.subscribe(function(response) {
// render `response` to the DOM however you wish
});
我也想知道如何处理just
操作符,因为在rxjs/add/operator里看不到...
I also want to know how to deal with just
operator, since I can not see it in rxjs/add/operator...
感谢您的帮助
推荐答案
RxJS 中有静态和实例操作符:
There are static and instance operators in RxJS:
static
of
interval
instance
map
first
你可能想像这样在 Observable
全局对象或 observable 实例上使用这些:
You may want to use these on the Observable
global object or observable instance like this:
Observable.of()
observableInstance.map()
为此,您需要从 add
包中导入模块:
For that you need to import modules from the add
package:
import 'rxjs/add/observable/of'
import 'rxjs/add/operator/map'
当你导入模块时,它本质上是通过添加与操作符对应的方法来修补 Observable
类或 Observable
原型.
When you import the module it essentially patches Observable
class or Observable
prototype by adding method corresponding to the operators.
但你也可以直接导入这些操作符,而不用修补Observable
或observableInstance
:
But you can also import these operators directly and don't patch Observable
or observableInstance
:
import { of } from 'rxjs/observable/of';
import { map } from 'rxjs/operator/map';
of()
map.call(observableInstance)
随着 [email protected] 中可出租操作符的引入,您现在应该利用内置的 pipe
方法:
With the introduction of lettable operators in [email protected] you should now take advantage of the built-in pipe
method:
import { of } from 'rxjs/observable/of';
import { map } from 'rxjs/operators/map';
of().pipe(map(), ...)
这篇关于如何从`rxjs` 包中正确导入操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!