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

Retrieve the specific object's methods based on a specified return type criteria

Initially, I have a class containing attributes and methods. My goal is to filter and retrieve only the keys of the methods. I created a utility type for this purpose and it worked smoothly: type FunctionPropertyNames<T> = { [K in keyof T]: T[K] e ...

Using Nestjs to inject providers into new instances of objects created using the "new" keyword

Is it possible to inject a provider into objects created by using the new keyword? For instance: @Injectable() export class SomeService { } export class SomeObject { @Inject() service: SomeService; } let obj = new SomeObject(); When I try this in my t ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Using inline style instead of relying on the quill editor's built-in classes, as classes may not be accessible in order to render HTML effectively

I have integrated the ngx-quill editor into my Angular project as the rich text editor. I plan to save the generated HTML in a database and display it on various browsers using innerHTML. Since the styling is done through a class attribute that references ...

Tips for adding icon to mat-sort-header within mat-table

Hi there, I'm currently working with mat-table in Angular and I have a question regarding adding a custom icon to the mat-sort-header. The issue I am facing is that when I click on the icon, the table gets sorted which is not the behavior I want. Belo ...

Steps for transferring .pem files to Typescript outDir

I am currently working on a NodeJS project using Typescript, and I have encountered an issue with referencing .pem files to initiate an https server. The problem arises when my code is compiled, as the .pem files are not present in the output directory. ...

Retrieving data from a form input that utilizes reactive checkboxes

Hey there, I am currently working on implementing a Reactive Form and facing an issue with fetching values from checkboxes. It seems that only the value of the first checkbox selected is being recognized while the others are not. Below is the snippet of my ...

In Angular, there is an issue where the @ViewChild decorator does not reflect changes when the value of the child component is updated within the

Does anyone know why the console.log("My status :", status); is not displaying after the child property has changed? Here is my child component code: @Output() public isLoggedIn: Subject<boolean> = new Subject(); constructor( private auth ...

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

Angular not utilizing prerendering

I've been struggling for a while now to implement Prerender.io in an Angular 6 project sample without any luck. Although I have managed to serve the application via Express, the page still fails to prerender. Below are the key files (and so far I ca ...

What is the best way to represent a state with two possible fields in React using TypeScript?

There is a specific state item that can have its own value or reference another item using an ID. interface Item { itemName: string; itemValue: { valLiteral: number } | { idNumber: string }; } const indItem1: Item = { itemName: "first sample&quo ...

How come validation errors are not appearing on the view?

As I continue to practice, I am working on this form. It successfully displays a console message, indicating the wiring is correct. However, an issue arises when I submit the form without entering any text in the input field, as it fails to show a validati ...

Angular causes HTML Dropdown to vanish once a null value is assigned

In my scenario, I have two variables named power and mainPower. Both of these variables essentially represent the same concept, with mainPower storing an ID of type Long in the backend, while power contains all attributes of this data transfer object. The ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

How to use D3 to add arrow directions to an SVG path

Within my svg path lies the representation of a shuttle track used in manufacturing processes. Every shuttle on this track moves in a distinct direction, and I wanted the svg path to visually indicate these directions for easy reference. Initially, I tried ...

What benefits does using Validators.compose() offer me?

I am in need of validating a field using multiple validators. If I opt for the Module Driven approach, my code will appear as follows: this.exampleForm = this.fb.group({ date_start : [ '', Validators.compose([ Validators.require ...

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

Error in Visual Studio with Angular 2 build: 'Promise' name not found

I recently started exploring Angular2 and followed the instructions provided in this quickstart guide: https://angular.io/guide/quickstart Everything seems to be working well after running npm install, but now I want to work on it within Visual Studio usi ...

Can data be transmitted in Angular without using a selector?

I am facing a challenge in sending data from a child component to its parent. The parent component's HTML code does not utilize the child's selector, as it is within a dialog of Angular Material and only uses "MatDialogRef" and "dialog.open()". T ...