Issue encountered when attempting to manipulate Observable data with the map function

Having trouble getting a list from HttpClient in Angular due to issues with transforming the data from an Observable.

Even after testing with static values, the results remain unchanged. Attempts at transforming values using map() within an Observable result in unmodified outputs. Consider the following examples:

import { from, map, Observable, of } from 'rxjs';

// Example 1:
const observableOne$: Observable<number[]> = of([1, 2, 3]);
observableOne$.pipe(
  map((items: number[]) => {
    console.log('This will be ignored');
    return items.map((item: number): number => item + 100);
  }),
  map((items: number[]) => {
    console.log('This will also be ignored');
    items.push(4);
  })
);
observableOne$.subscribe((items: number[]) => console.log('First:', items));
// Output will be:
// First: [1, 2, 3]

// Example 2:
const observableTwo$: Observable<number> = from([1, 2, 3]);
observableTwo$.pipe(map((item: number) => item + 100));
observableTwo$.subscribe((items: number) => console.log('Second:', items));
// Output will be:
// Second: 1
// Second: 2
// Second: 3

Any ideas on how to address this issue?

Answer №1

Utilizing a pipe() function will not alter the original Observable. Instead, it generates a fresh Observable that necessitates subscription from someone else. Therefore, when you subscribe to ObservableOne$, you merely receive the initial emitted values.

You must subscribe to the Observable produced by the pipe function.

const observableOne$: Observable<number[]> = of([1, 2, 3]);

observableOne$.pipe(
  map((items: number[]) => {
    console.log('This will be disregarded');
    return items.map((item: number): number => item + 100);
  }),
  map((items: number[]) => {
    console.log('This will also be disregarded');
    items.push(4);
    return items
  })
).subscribe((items: number[]) => console.log('First:', items));

Additionally, please take note that you omitted the return statement in your second map function. Without a return statement within a map function, it will simply output undefined, which gets passed down the chain.

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

What is the correct way to implement ramda's ifElse function in typescript?

My attempt to enhance the typing of ifElse in Ramda, which currently has a type definition as follows: export function ifElse(fn: Pred, onTrue: Arity2Fn, onFalse: Arity2Fn): Arity2Fn; However, I quickly reached the limitations of TypeScript (or rather my ...

Encountering a TypeScript Error when trying to customize the MUI color palette

I'm attempting to incorporate a custom color in MUI v5 using TypeScript, but I keep receiving the error: Type '"my_custom_color"' is not allowed for type '"primary" | "inherit" | "secondary" | "success" | "error" | "info" | "warning" ...

Encountering a Vueify Typescript error in a Vue project

Recently diving into the world of Vue, I was able to successfully create a sample app using gulp, vueify, and TypeScript. To showcase what's happening and shed light on an issue I'm facing, here are snippets of the key code segments: Menu.ts im ...

Extending the Request type from Express with Typescript

Having a NodeJs app with Express and Typescript, I am attempting to extend the Request type from Express. I have created an index.d.ts file with the following code snippet: import { User } from "models/user"; declare global { namespace Expres ...

typescript create object with some properties using object literal

Is there a way to initialize an instance of a class with an object literal that doesn't contain all the elements in the class, but those present are part of the class? class Example{ text:string; number:number; displayResult(){return thi ...

What is the process for assigning a value to a property?

I am currently developing an Angular application that utilizes reactive forms. I need to retrieve the values of dynamically created fields within a form group. Here is the code I have implemented: this.formSaisieSecondary = this.fb.group({ ...

What is the process for incorporating an external file into Angular CLI?

I have a project where I am trying to extract element details from an HTML file using the Angular CLI. However, I encountered an error while using PHP to fetch the file content: ./bodycontent/load.php file not found... zone.js:2933. Does anyone know how ...

PlayWright - Extracting the text from the <dd> element within a <div> container

Here is the structure I am working with: <div class="aClassName"> <dl> <dt>Employee Name</dt> <dd data-testid="employee1">Sam</dd> </dl> </div> I am attempting to retrie ...

Having trouble with your Typescript *.ts files?

Having trouble understanding why the command tsc *.ts isn't functioning correctly. The error message TS6053: File '*.ts' not found keeps appearing. Any suggestions on how to compile all the .ts files within a directory? Thank you! ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

After running a yarn build on a TypeScript project using a .projenrc.js file, make sure to include any packaged or additional text files in the lib folder, rather

After utilizing projen to create my typescript project, I followed these steps: mkdir my-project, git init, and npx projen new typescript. Additionally, I created two files - sample.txt and sample.js, along with the default file index.ts within the folder ...

Tips for showing data from an hour ago in Angular

Here is the code snippet provided: data = [ { 'name' : 'sample' 'date' : '2020-02-18 13:50:01' }, { 'name' : 'sample' 'date' : '2020-02- ...

Infinite Loop Issue in Angular2 RC5 when using the templateUrl

Encountering an issue with Angular2 RC5 that seems to be causing an infinite loop problem. The app.component, which is bootstrapped by the app.module, appears quite simple: @Component({ selector: 'my-app', template: `TEST` }) export cl ...

Confirm that a new class has been assigned to an element

I'm having trouble creating a unit test for a Vue.js component where I need to check if a specific CSS class is added to the template. Below is the template code: <template> <div id="item-list" class="item-list"> <table id="item ...

An error was encountered at line 7800, character 18 in the three-core.d.ts file in the node_modules/@types/three directory. The error message reads: "Cannot find name 'VRDisplay

I encountered an error in my Angular 6 app while running ng serve ERROR in node_modules/@types/three/three-core.d.ts(7800,18): error TS2304: Cannot find name 'VRDisplay'. node_modules/@types/three/three-core.d.ts(7801,23): error TS2304: Canno ...

Problem with Angularfire: The type 'Promise<any>' does not have a property called 'subscribe'

Whenever I try to retrieve data from the database, an error message crops up: "The property subscribe is not recognized within type Promise<any>." What steps should I take to fix this issue? This snippet showcases my code: getUsers(){ retur ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

Using Typescript with Vue to create a reactive exported variable

Scenerio Setup Currently, I have developed a Vue3 + Firebase project which includes an object called userInfo in the main.ts file. The export declaration is as follows: export var userInfo :any = {} It is important to note that the :any declaration is ...

Guide to running two consecutive NPM commands with the final step being the duplication of a file

I have made changes to my package.json scripts as recommended in this post and also in this one. The modification functions correctly and produces the expected results. ... "deploy": "ng build && echo Do not forget to copy web.config!", ... Subse ...

Update the UI with changes from the BehaviorSubject after receiving the HttpClient response

I am currently working on a small service that makes a POST request to the backend. The response from this POST request should be added to a BehaviorSubject which is then used in various parts of the Angular application. While I can see a new record being ...