I need to do something quit simple - I would like to do a one time http request to a static data - I would like to do it either when the application starts or as "lazy-loading", when needed. I would like to send the http request one time and set a variable (member -> property) with the returning results, so I can use that property later on instead of doing another http request. Below is my code - is it the best practice solution ? Any remark\improvement\another way of doing it - would be appreciated.
The "lut" is for "lookup table" dat -> the static data.
@Injectable({providedIn: 'root'})
export class lutData
{
_someData : somedataType[] = null;
constructor(private lutService : LutService){} //The service is a simple http service
public get SomeData() : somedataType[] {
if (this._someData){
return this._someData;
}
else {
this.lutService.getSomeLutData().subscribe(result =>{
this._someData = result;
return this._someData;
});
}
}
}
This is the component that should use the data: I'm using injection, but maybe there's a better way doing it.
export class XXX_Component {
someData : somedataType[];
constructor(private lookUpData : lutData) { }
ngOnInit() {
this.setLutData();
}
setLutData() {
this.someData = this.lookUpData.SomeData;
}
}
subscribe().return this._someData;isn't doing anything at all. Also you should consider using operators such as shareReplay which useReplaySubjectunder the hood to "cache" n number of results.