Reputation: 49
service.ts
@Injectable({
providedIn:'root'
})
export class textAppService{
constructor(private http: HttpClient){}
getPersonDetail(id:any):Observable<any>{
return id? this.http.post(ur;, {id:id}):of(new personDetails());
}
}
· so I want to pass the data I got from getPersonDetail() method to some other non relation componenet ts file, and I cannot call the getPersonDetail() service to do that due to the time efficiency. So what should I do. would I be able to set the data I got from the getPersonDetail as a global object, so it can be used in several componenet?
Upvotes: 1
Views: 53
Reputation: 22213
You can use BehaviorSubject to detect change.
Create a service like:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DetectPersonChangeService {
constructor() { }
public status: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
changeData(value: any) {
this.status.next(value);
}
}
On getPersonDetail()
sunscribe, call the service,
this.DetectPersonChangeService.changeData(data);
and to detect the change in unrelated component:
this.DetectPersonChangeService.status.subscribe((val) => {
console.log(val)
});
Upvotes: 1
Reputation: 141
There are multiple ways to achieve what you want. Simplest option is to cache the data in some variable and check if the data is already set for the given id and return from the cache instead of making the call. You can even use an interceptor to cache the data and prevent polluting your service calls. Refer this link for examples Link
Upvotes: 0