I have implemented a configuration to share the replay of my httpClient request among multiple components. Here is the setup:
apicaller.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// import rxjs map
import { map, shareReplay } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class ApicallerService {
peopleindex: number = 1;
constructor(private _http: HttpClient) {}
private readonly request = this._http
.get('https://swapi.dev/api/people/' + this.peopleindex)
.pipe(shareReplay());
getData(peopleindex: number = 1) {
this.peopleindex = peopleindex;
return this.request;
}
}
Component1
This component should request the API to retrieve details for id 2
import { Component, OnInit } from '@angular/core';
import { ApicallerService } from '../apicaller.service';
@Component({
selector: 'app-component1',
templateUrl: './component1.component.html',
styleUrls: ['./component1.component.css'],
})
export class Component1Component implements OnInit {
apiresponse: any;
editRes: any;
constructor(private _apicaller: ApicallerService) {}
ngOnInit(): void {
this._apicaller.getData(2).subscribe((data: any[]) => { // <-- Notice 2 in the argument
console.log(data);
this.apiresponse = data;
});
}
}
Component2
This component requests data for the default ID
import { Component, OnInit } from '@angular/core';
import { ApicallerService } from '../apicaller.service';
@Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
apiresponse: any = {};
constructor(
private _apicaller: ApicallerService
) { }
ngOnInit(): void {
// get data from api using service
this._apicaller.getData().subscribe(
(data) => {
this.apiresponse = data;
}
);
}
}
However, there seems to be an issue where component1 is not making a new request with peopleindex = 2
.
To see and reproduce the problem, you can check out my StackBlitz setup here: https://stackblitz.com/edit/angular-ivy-gdxyy6?file=src%2Fapp%2Fcomponent1%2Fcomponent1.component.ts