Madan
Madan

Reputation: 77

Angular: Declare global constant in service

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.

Upvotes: 0

Views: 879

Answers (2)

Avid Coder
Avid Coder

Reputation: 18387

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.

Upvotes: 1

Guerric P
Guerric P

Reputation: 31805

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.

Upvotes: 0

Related Questions