What are the important steps to properly map data prior to subscribing?

I'm working on a function that looks like this:

    this.localStorage.getItem('user').subscribe(user => {
      this.user = user;
      this.authSrv.getOrders(this.user.einsender).pipe(map(orders => {
        map(order => { order["etz"] = "23"; return order})
        return orders;
      })).subscribe(orders => {
        this.orders = orders;
        this.completeOrders = orders;
        console.log(orders);
        this.waitUntilContentLoaded = true;
      })
    })

When I run the function without the map, the result is:

[{id: 1, etz: "21"}]

After adding the map to loop through the array, update the order and set a new value for the etz property, the change doesn't seem to be taking effect. Can someone take a look and provide some assistance? Your help is greatly appreciated!

Answer №1

It appears there are several issues that need addressing.

  1. Avoid using nested subscriptions by utilizing RxJS higher order mapping operators such as switchMap. You can explore the variances between different higher order mapping operators here and here.

  2. To modify each element of the array, make use of the Array#map method along with the RxJS map operator.

  3. Consider leveraging the JS spread operator to adjust specific properties of an object while retaining others.

Here is a suggestion:

this.localStorage.getItem('user').pipe(
  switchMap(user => {
    this.user = user;
    return this.authSrv.getOrders(this.user.einsender).pipe(
      map(orders => orders.map(order => ({...order, order['etz']: '23'})))
    });
  })
).subscribe(
  orders => {
    this.orders = orders;
    this.completeOrders = orders;
    console.log(orders);
    this.waitUntilContentLoaded = true;
  },
  error => {
    // It's recommended to handle HTTP errors
  }
);

Answer №2

map is a special operator that can be utilized within a pipe as shown below:

someObs$.pipe(map(arg => { return 'something'}));

However, in the code snippet you provided, it seems like there is a redundant use of map:

someObs$.pipe(map(arg => { 
    map(arg => { return 'something' })     // this line here serves no purpose
    return arg; 
}));

Using map inside the function passed to map doesn't have any logical significance.

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

Focusing on a specific image using Jquery

I am looking to specifically target the image within the "hero1project3" class, however, the image is currently set as a background. Is there a way in jQuery to apply effects like blur only to the image itself, for example, using ".hero1project3 img"? HTM ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Guide on deploying multiple applications under a single URL with S3 on Amazon Web Services

I am working on deploying multiple Angular and React apps on AWS through S3. Currently, one of my Angular apps is successfully running when accessing mysite.com. It functions properly as intended. I am looking for a way to load different apps based on th ...

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...

Attention: It is not possible to update the React state on a component that is not mounted. Please use the useEffect cleanup function

Can you assist with solving this issue? https://i.sstatic.net/yKFzr.png //ReviewProductDetail.jsx : Initially, the page was populated from this particular component import React, { useEffect, useState } from 'react'; import RatingCardProductD ...

Struggling to incorporate method decorators to handle http errors in Angular?

My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet: createRecord(data: data) { return this.httpClient.post(`${this.apiURL}/record/`, data); } I am looking to refactor thes ...

Loading large content using jQuery's .html() method

After experimenting with the jQuery .html() function, I've noticed that it struggles to handle large amounts of text. You can see an example of this issue. Fortunately, a much simpler test case works perfectly fine. While I understand that including ...

The currency exchange script is malfunctioning and not functioning properly

Is there a solution for accessing the JSON value that is currently eluding me? If anyone has any suggestions, I would greatly appreciate it. function forex() { var to = document.getElementById("to").value; alert(to); var from = document.getE ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...

Ways to permit https://* within a content security policy (CSP) configuration

I'm currently incorporating CSP into my website but encountering an issue with the img-src header. I'm using NodeJS and Express to develop the site for my Discord Bot, and I want to revamp it but I've hit a roadblock. ====== This is the co ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Tips on changing the URL of the current tab after clicking on a link

const selenium = require('selenium-webdriver'); require('chromedriver'); const By = selenium.By; const driver = new selenium.Builder().forBrowser('chrome').build(); const url = 'https://example.com'; driver.get(url) ...

Accessing dynamically created AJAX controls in ASP.NET during postback operations

I am dynamically creating 2 dropdown boxes and a CheckBoxList control using AJAX callbacks to a web service (.asmx file). The server-side service generates the Dropdowns and CheckBoxList, returning the rendered html as a string which is then inserted into ...

Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this: const arrayOfArrays: number[][] = [[1, 2], [1, 3]]; The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]]. I found a solution using the following approach: // initialize an e ...

Error: The property 'match' is undefined and cannot be read by Object.j during rendering in angular-datatables.min.js at line 6

I am currently using angular-datatables.min.js for my data table, but I have encountered an error that I have been unable to resolve. Is there anyone who can provide assistance with this issue? App.controller('DailyTaskListController', ['$s ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...

How to transfer a C library callback to a NodeJS EventEmitter with the help of node-addon-api

In the process of developing a node module that integrates Alex Diner's cross-platform gamepad code using the Node-Addon-API, I encountered an interesting challenge. Making the module function as an EventEmitter and exposing callback functions throug ...

Unable to retrieve a substring value in Angular using Typescript

html <p> <input type="text" maxlength="40" (input)="recipientReference = deleteSpacing(recipientReference)" [(ngModel)]="recipientReference" style="width: 30vw; padding: 5px;border: 1px solid;border ...