Update Observable by assigning it a new value of transformed information using the async pipe and RXJS

My service always returns data in the form of Observable<T>, and unfortunately, I am unable to modify this service.

I have a button that triggers a method call to the service whenever it is clicked. This action results in a new Observable being returned. Utilizing the async pipe allows me to update the UI with the new data.

Currently, I am interested in transforming this data but only when the user clicks the button. I attempted to use the map function to perform the transformation and return the updated data, however, my efforts were in vain. Could there be something crucial that I overlooked?

Thank you for your help as I navigate through my learning journey with RXJS.

Explore Source Code and Experiment on StackBlitz

html

<h1>{{ random$ | async }}</h1>

<button (click)="buttonClick()">Get new Random number</button>

<button (click)="transformButtonClick()">Transform</button>

ts

import { Component, Injectable, OnInit } from '@angular/core';
import { map, Observable, of } from 'rxjs';

@Injectable()
export class Service {
  // The code within this class cannot be altered
  public getRandom(): Observable<number> {
    return of(Math.random());
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  constructor(private service: Service) {}

  public random$: Observable<number> = new Observable<number>();

  ngOnInit(): void {}

  buttonClick(): void {
    this.random$ = this.service.getRandom();
    // The transformation cannot be performed here since the user's intention is unknown
  }

  transformButtonClick(): void {
    // How can I multiply the random data by 10?
    this.random$ = this.random$.pipe(
      map((data) => {
        data * 10;
        return data;
      })
    );
  }
}

Answer №1

It seems like the issue might be with the map operator where you are not returning the * 10 value.

In addition, consider creating a new observable to store your transformed data instead of reassigning it to the original $random observable.

// Consider trying something like this
export class AppComponent implements OnInit {
  constructor(private service: Service) {}

  public random$: Observable<number> = new Observable<number>();
  public randomTimesTen$: Observable<number> = new Observable<number>();

// ...

  transformButtonClick(): void {
    this.randomTimesTen$ = this.random$.pipe(
      map((data) => {
        return data * 10;
      })
    );
  }

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

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Recently updated from Angular 9 to 14 and noticed a peculiar issue in the deployed app - all API calls seem to only reference the root or hosted URL in the request URL

After upgrading the application from angular 9 to angular 14, I encountered a network call issue. The application was successfully deployed via azure devops, but all network calls were directed to the host URL instead of the expected API endpoints. For exa ...

NPM displaying an error message

npm ERROR! Windows_NT 6.3.9600 npm ERROR! Command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\np ...

Learn how to access nested arrays within an array in React using TypeScript without having to manually specify the type of ID

interface UserInformation { id:number; question: string; updated_at: string; deleted_at: string; old_question_id: string; horizontal: number; type_id: number; solving_explanation:string; ...

The OrderBy Pipe in Angular 4 fails to sort correctly when the name of the item being sorted

How can I sort names ending with numbers using a custom pipe? I have successfully implemented a custom pipe for sorting and it is working as expected. $Apple fruit -symbol 1Apple fruit -numbers Apple fruit -alphabetically However, the custom pip ...

The Angular 2 error message states that the type 'Observable<{}>' is not compatible with the assigned type

Observable is having trouble being assigned, my package.json file contains "angular2": "2.0.0-beta.17", "systemjs": "0.19.24", "es6-promise": "^3.0.2", "es6-shim": "^0.35.0", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.6", "zone.js": "0.6.12" The is ...

Expressions without a call signature cannot be invoked

When using an adapter in the given example, I encountered a type error specifically on the last line of the getGloryOfAnimal method. Despite having clearly defined types, I am puzzled by this issue. interface ICheetah { pace: string; } interface ILio ...

Sorting in the TypeScript/Angular table is functioning properly on every column except for the initial one

Even after carefully following the information provided in the official documentation and implementing the example as suggested, I'm still struggling to sort my first column in descending order. Whenever I attempt to sort by another column and then cl ...

What is the best way to create Jest unit tests for an Angular Component without using TestBed?

I'm diving into the world of Jest testing and feeling lost as to why my tests keep failing. If you have any recommendations for videos or articles that focus on writing Jest unit tests for Angular components and services without using "TestBed," plea ...

Displaying an array assigned within an Angular class

I'm facing an issue displaying a list of content using an array in Angular. Despite the app functioning properly, no data seems to be returned. Other apps are loading fine. Although the service has been added to the app.module.ts file, there are no e ...

Can I prevent users from selecting Today and future dates in Angular with ngx-bootstrap datepicker?

Hi there, I'm new to Angular and could use some assistance. I tried using the following code snippet to disable today and future dates: <input class="form-control" placeholder="Datepicker" ngMod ...

Access a document and analyze its information

I am currently working with a file upload control that stores the selected file within it, as shown in the code snippet below: <div class="Block"> <label id="lbl">File </label> <input #fileInput type='file'/> </div ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Is it possible for React props to include bespoke classes?

In our code, we have a TypeScript class that handles a variety of parameters including type, default/min/max values, and descriptions. This class is utilized in multiple parts of our application. As we switch to using React for our GUI development, one of ...

Mastering the Art of Handling Postgres Error Messages for Accurate Query Execution

Currently, I am utilizing pg and node.js. The issue arises when a user logs in through the auth0 widget, as I am passing the returned email to check against my database for existing users. If the user does not exist, I am inserting their information into t ...

What is the best way for me to access a certain web address?

I am working on setting up a routing mechanism in my Angular project, but I'm encountering a URL routing error. The application is unable to locate the specified URL. Below is the routing setup: navigation.ts { id: 'documentation-manag ...

Tips on launching a bootstrap modal by clicking a button in an Angular project

I'm working with a Bootstrap Modal that includes a button to trigger it. Here is the code: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data- ...

Starting a nested JSON structure with TypeScript and Angular 7

I'm encountering an error when attempting to make a POST request by sending an object TypeError: Can not set property 'ItemCode' of undefined My setup involves Angular 7 and Typescript Here is my initial JSON: objEnvio:any = <an ...

Organize data in the store using @ngrx/data and @ngrx/entity, rather than within the component (subscriber)

When working with the ngrx/data library, I often find myself having to manipulate and format data from the store in various parts of my application. While I have utilized the filterFn function to retrieve only the relevant entities for my use case, I am st ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...