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;
})
);
}
}