Issue with Switch Map in Angular 2 and RxJS

I'm currently implementing an infinite scrolling feature in my application using a specific component for managing scroll events. When the scroll reaches the bottom of the div, I trigger a function to fetch more data. Everything seems to be working fine so far.

In order to optimize this process, I want to introduce a delay before making the call and ensure that the retrieved data is processed correctly. Following an example on the Angular website featuring a Wikipedia search, I attempted to implement a similar setup.

However, upon calling switchMap(), I encountered the error message:

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

This excerpt showcases part of my code:

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

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

...

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

The screenshot below illustrates the issue:https://i.sstatic.net/PqyB2.png

In my investigations, it appears to be related to returning the Observable (Type 'void' is not assignable to type 'ObservableInput<{}>'). However, I am struggling to pinpoint the exact problem in my case.

My environment includes:

  • Angular 4.0.1
  • TypeScript 2.2.2
  • RxJS 5.2.0

Answer №1

If you do not explicitly return a value in an arrow function () => {...}, it will have a default return type of void.

To utilize switchMap to return nothing, simply follow the advice provided by yurzui in the comments: return Observable.empty().

However, if you find yourself returning an observable with a null value in your switchMap, then it may be worthwhile to consider using the do operator instead. The do operator allows you to perform an action without altering the data being returned. Similarly, you can also explore using the mergeMap operator which enables you to generate a new Observable based on the data retrieved from the original one.

Answer №2

Currently using:

  • Angular 6.2.1
  • TypeScript 3.0.1
  • RxJS 6.3.3

Facing a similar challenge, I found a solution by ensuring that switchMap always returns a valid value and not undefined or null. If returning an Observable is not possible, returning an empty array can be a workaround.

To resolve a complex Observable sequence, I came up with the following approach:

resolve(): Observable<any> {
    return firstObservableFunc()
    .map(res => res)
    .switchMap(result => (result && result.value === 'OK') ? secondObservableFunc() : []);                        
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging unit tests can be a headache in Angular using Jasmine

I'm finding it really challenging to set up the testing module for my unit tests in Angular. The issue I'm facing is that I struggle to identify all the dependencies I need. My current approach is to start karma with ng test and then check the e ...

Launch another modal and then deactivate the initial modal

Having two Modals has presented a challenge for me when it comes to closing the first modal after the second one is opened. I attempted a solution, but it prevented the second Modal from opening altogether. This code snippet below belongs to the first Mo ...

Accessing JSON data from a database using Angular

Wondering if there is a way to effectively access and manipulate JSON data stored in a database using Angular. While researching online, I keep coming across methods for reading JSON files from the Asset Folder, which does not align with what I need. What ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Leveraging Leaflet or any JavaScript library alongside Typescript and webpack for enhanced functionality

Important: Despite extensive searching, I have been unable to find a resolution to my issue. My current endeavor involves developing a map library through the extension of leaflet. However, it appears that I am encountering difficulties with utilizing js ...

Angular populates the id property of the mode with the dropdown's display value instead of the actual id

I successfully implemented a dropdown in my Angular application, but I am facing an issue when submitting the form. Instead of displaying the Id, it is showing the display text in the model. What could be causing this problem? To my understanding, all I ne ...

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

Searching for a specific document using AngularFirestore - what's the best method?

Is it possible to create an Observable that is limited to a single document? While the code provided creates an Observable for querying multiple documents: foo.component.ts import { AngularFirestore } from '@angular/fire/firestore'; import { O ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Sharing data across multiple components while navigating in Angular is a common requirement. By passing

I have a specific structure set up in my application: <div class="container"> <top-navbar></top-navbar> <router-outlet></router-outlet> <navbar></navbar> </div> The components I have include Top ...

Customizing tsconfig.json: Enhancing an existing object by adding new keys in TypeScript

Is it possible to achieve the following functionality by default? let j = {a:1}; j.b = 2; I am aware that there are alternative solutions, but I am curious if this specific task can be accomplished by solely modifying tsconfig.json? ...

What is the process for integrating GraphQL resolvers in Typescript using Graphql-codegen?

With the goal of learning Apollo Server, I decided to implement the schema outlined here. The CodeGen produced what seemed to be logical type definitions for books and libraries. export type Book = { __typename?: 'Book'; author: Author; tit ...

Combining vue with deno and vscode: A guide to seamless development integration

How can I set up Visual Studio Code for a Vue project using Deno? Important note - the issues mentioned here only pertain to highlighting in VSCode, as the builds, development, and scripts are functioning correctly! Deno + Vue is an appealing choice! You ...

When running ng new command, an error may occur with dryRunSink.(...).concat not functioning properly

I've been attempting to create a new Angular project by following the steps outlined on this website: https://github.com/angular/angular-cli However, each time I try to initiate a new project using the ng new command, an error occurs. E:\Code&b ...

Enforcing uniform data types in nested objects in TypeScript

Currently, I am in need of generating a list of constants. For instance, const Days = { YESTERDAY: -1, TODAY: 0, TOMORROW: 1, } I am looking for a method to restrict the types of all properties within Days. In other words, if I attempt to add a pr ...

The formatting directive fails to keep pace with speedy input

I am working on a feature to automatically format the input field as the user types, transforming the letters into valid initials in uppercase with dots in between. The formatting needs to happen in real-time as the user inputs characters, rather than aft ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Tips for transferring several parameters from an Angular 8 application to a .NET Core API

Hello, I am facing an issue with passing multiple string parameters from an Angular 8 app to a .NET Core API. This is my first time posting a question so I will try to provide all the necessary details. Here is the Angular code snippet: import { Injectab ...

Using the slice pipe on the data for a child component property is resulting in endless calls to the @Input set method

After incorporating a slice pipe into the data object below and passing that data to the child component's @Input method, there appears to be an endless loop of calls to that method. However, eliminating the slice pipe from the data object resolves th ...