I'd like to call a service which calls a REST API, and uses the returned data to set a global constant variable that can then be accessed within components throughout the app. I'm not sure of the best way to proceed with this.
Asked
Active
Viewed 459 times
2 Answers
1
Just make your service root-level and inject it in other services and components like ..
@Injectable({providedIn: 'root'})
export class MyService {
data;
constructor(private http: HttpClient) {
this.http.get('some-url').subscribe(data => this.data = data);
}
}
Now any component can grab the data from the root-level service.
@Component({
selector: 'my-component',
template: '<div>Hello</div>',
})
export class MyComponent {
myData;
constructor(private myService: MyService {
this.data = this.myService.data;
}
}
The above code is for example only.

Val Neekman
- 17,692
- 14
- 63
- 66
-
This fits my case very well. Is there a way to make it so that if the API call takes some time then the service constructor will wait on it, so that when the component accesses the data variable it will not be undefined? – Madan Mar 16 '20 at 22:08
-
I ended up using the APP_INITIALIZER dependency injection token as described here https://stackoverflow.com/questions/50299147/how-can-i-make-angular-5-wait-for-a-promise-used-inside-an-injectables-construc – Madan Mar 16 '20 at 23:21
-
Alternatively you can use https://github.com/un33k/ngx-cfg to manage all your local/remote cfgs – Val Neekman Mar 19 '20 at 17:30
0
A service is a singleton by default (one instance for the whole app) so everything you store in a service will be shareable to every component in your app.

Guerric P
- 30,447
- 6
- 48
- 86
-
Not true, unless it uses { providedIn: 'root' }, otherwise you can have multiple copies – Val Neekman Mar 16 '20 at 21:21
-