Can you explain the distinction between employing 'from' and 'of' in switchMap?

Here is my TypeScript code utilizing RxJS:

function getParam(val:any):Observable<any> {
        return from(val).pipe(delay(1000))
    }

    of(1,2,3,4).pipe(
        switchMap(val => getParam(val))
    ).subscribe(val => console.log(val));

I believe that the getParam function should return 'val' within an observable. However, I encounter an error with switchMap stating:

hostReportError.js:5 Uncaught TypeError: You provided '1' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:39)
    at Module.from (from.js:15)
    at getParam (index.ts:6)
    at SwitchMapSubscriber.eval [as project] (index.ts:8)
    at SwitchMapSubscriber._next (switchMap.js:43)
    at SwitchMapSubscriber.Subscriber.next (Subscriber.js:63)
    at Observable.eval [as _subscribe] (subscribeToArray.js:7)
    at Observable._trySubscribe (Observable.js:50)
    at Observable.subscribe (Observable.js:36)
    at SwitchMapOperator.call (switchMap.js:27)

If I modify the getParam function to:

function getParam(val:any):Observable<any> {
    return of(val).pipe(delay(1000))
}

It successfully returns 4. So why does the from operator not return an observable in this scenario?

Edit: This question is distinct from RxJs Observable of vs from because it focuses on the fact that both from and of should be observables. Yet, when using from, switchMap raises an issue about not receiving an observable and simply obtaining '1' from the array. I hope this clarifies the inquiry.

Answer №1

An issue occurred that did not originate from switchMap.
The function getParam(val: any) received a number which could not be accepted as an input by from(), but of() can handle it


    hostReportError.js:5 Uncaught TypeError: 
      Instead of a stream, you provided '1'. 
      Acceptable inputs include Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:39)
    at Module.<b>from</b> (from.js:15)

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

Tips for concealing backend data in Angular2 under the conditions where the name is designated as anonymous and the nested array is empty

I'm dealing with an array of data fetched from the backend and I need to meet the following requirements: If the user's name, "from_user_name", is Anonymus, then the contents must be hidden. Hide the messages if the array is empty. Can someone ...

Utilizing a component from a different module

Currently working on Angular 4 and facing an issue with referencing a component from another module. In my EngagementModule, the setup is defined as below: import { NgModule } from '@angular/core'; // other imports... @NgModule({ imports: [ ...

Unable to retrieve information from a function in Vue.js (using Ionic framework)

When attempting to extract a variable from a method, I encounter the following error message: Property 'commentLikeVisible' does not exist on type '{ toggleCommentLikeVisible: () => void; This is the code I am working with: <template& ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

What are the steps to lift non-React statics using TypeScript and styled-components?

In my code, I have defined three static properties (Header, Body, and Footer) for a Dialog component. However, when I wrap the Dialog component in styled-components, TypeScript throws an error. The error message states: Property 'Header' does no ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

An error occurs with webpack during postinstall when trying to load TypeScript

I have created a custom package that includes a postinstall webpack script as specified in my package.json file: "scripts": { ... "postinstall": "webpack" } The webpack configuration looks like this: const path = require('path'); ...

Navigating the world of Typescript: mastering union types and handling diverse attributes

I am currently working on building a function that can accept two different types of input. type InputA = { name: string content: string color: string } type InputB = { name: string content: number } type Input = InputA | InputB As I try to impleme ...

Error message: There appears to be a type error within the labelFunc of the KeyBoardDatePicker component in the Material-UI

I am currently working with a material-ui pickers component: <KeyboardDatePicker value={selectedDate} onChange={(_, newValue) => handleClick(newValue)} labelFunc={renderLabel} disableToolbar variant='inline' inputVariant=& ...

The class 'GeoJSON' is mistakenly extending the base class 'FeatureGroup'

Encountering an error message in one of my projects: test/node_modules/@types/leaflet/index.d.ts(856,11): error TS2415: Class 'GeoJSON' incorrectly extends base class 'FeatureGroup'. Types of property 'setStyle' are incompa ...

Why is Zod making every single one of my schema fields optional?

I am currently incorporating Zod into my Express, TypeScript, and Mongoose API project. However, I am facing type conflicts when attempting to validate user input against the user schema: Argument of type '{ firstName?: string; lastName?: string; pa ...

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

Tests in headless mode with Cypress may fail sporadically, but consistently pass when running in a real browser

Currently, I am utilizing Cypress 9.5 to conduct tests on an Angular 13 application with a local PHP server as the backend. Throughout the testing process, I have encountered successful results when running the tests in the browser multiple times. However ...

Populate a chart in real-time with data pulled directly from the Component

I'm completely new to Angular and I feel like I might be overlooking something important. Within my component, I have 3 variables which are populated after invoking the .subscribe method on an observable object. For example: this.interRetard = this ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test"> <mat-radio-button *ngFor="let option of options | filter:searchText" class="cssForRow" [value]="option" ...

Tips for ensuring the correct typing of a "handler" search for a "dispatcher" style function

Imagine having a structure like this: type TInfoGeneric<TType extends string, TValue> = { valueType: TType, value: TValue, // Correspond to valueType } To prevent redundancy, a type map is created to list the potential valueType and associate i ...

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...