I am new to Angular and struck with subscribe method. I need to trigger subscribe first in which initialization of property is done. Please help me with this. Here is my code..
json.service.ts
@Injectable({providedIn: 'root'})
export class JsonService {
constructor(private http: HttpClient) {}
//This fetch the json present in assets folder
url: string = `${window.location.origin}/assets/urls-list.json`;
getRestJson() {
this.http.get(url);
}
url.setting.ts
@Injectable({providedIn: 'root'})
export class UrlService {
fetchedJson: Array<any>;
constructor(private service: JsonService) {
this.fetchingJsonFromService();
}
fetchingJsonFromService() {
this.service.getRestJson().subscribe(
response => {
this.fetchedJson = response;
});
}
private static getValue(key: string) {
// use the key do some stuff with "this.fetchedJson"
and return only that value back to getServiceUrl()
return something;
}
public static getServiceUrl(key:string) {
const result = UrlService.getValue(key);
return result;
}
}
From debugging this code realized that "getValue()" is called first and the "this.fetchedJson" is undefined. Then the call goes to "fetchingJsonFromService()" where fetchedJson gets initialized which is too late. Kindly help me to solve this issue. It would be of great help.
"getServiceUrl(key)" - is called by multiple services throughout the application
Thanks a lot!!