Search code examples
angularangular-services

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.


Solution

  • 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.