Angular 2-RxJS开关映射问题 [英] Angular 2 - RxJS Switch Map Issue

查看:79
本文介绍了Angular 2-RxJS开关映射问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在应用程序中包含一个无限滚动部分.为此,我使用此组件来处理滚动事件,依此类推.当滚动到达div的底部时,我正在调用一个函数以获取更多数据.到目前为止一切顺利.

I'm trying to have an infinite scrolling section in my application. To achieve this I'm using this component to handle the scroll events and so on. When the scroll reaches the bottom of the div I'm calling a function to get more data. So far so good.

为使此功能更有效,我尝试在调用之前等待几秒钟,并确保正确处理了数据.为此,我一直在查看

To make this function more efficient I'm trying to wait a few seconds before the call is made as well as make sure that the data is processed properly. To do this I've been looking at the example shown on the Angular website that showcases a wikipedia search.

我有与本文中显示的类似的设置,我的问题是调用switchMap()时出现以下错误:

I have a similar setup to what is being shown in the article, my problem is that I'm getting the following error when I call switchMap():

Type 'void' is not assignable to type 'ObservableInput<{}>'

这是我的代码的示例:

private scrollEndActive: Subject<boolean> = new Subject<boolean>();

ngOnInit() {
    ...
    this.scrollEndActive
        .debounceTime(1000)
        .distinctUntilChanged()
        .switchMap(data => {
            // ... get data from server
        })
}

...

// event to trigger call to server
scrollEnd() {
    this.scrollEndActive.next(true);
}

使用上面的代码,这就是我得到的:

With the code above this is what I'm getting:

根据我的研究,这似乎与一个事实有关,即应该返回Observable().但就我而言,我不确定是什么问题.

From the research I've made it seems to be an issue related to the fact that one should return the Observable (Type 'void' is not assignable to type 'ObservableInput<{}>'). But in my case I'm not sure what is the issue.

我正在使用:

  • 角度4.0.1
  • TypeScript 2.2.2
  • RxJS 5.2.0

推荐答案

默认情况下,箭头函数() => {...}的返回类型为void,除非您返回某些内容.

By default, an arrow function () => {...} has the return type void unless you return something.

如果您想使用switchMap不返回任何内容,则可以按照yurzui在评论return Observable.empty()中所说的那样进行.

If you want to use switchMap to return nothing, you can do as yurzui said in the comments, return Observable.empty().

话虽如此,如果您在switchMap中返回一个可观察到的null,则意味着您不需要switchMap,并且可以直接使用do运算符,该运算符无需更改返回的数据即可执行操作.或mergeMap允许您从原始数据中返回一个新的Observable.

That being said, if you return an observable of null in your switchMap, it means that you don't need switchMap and you can directly use do operator, that doesn an action without modifying returned data. Or mergeMap that allows you to return a new Observable from the data you got from the original one.

这篇关于Angular 2-RxJS开关映射问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆