Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular4 - create a global variable that can be also accessed in views

Tags:

angular

Is it possible to create a global variable that can be accessed from both components and views?

At the moment i created a global.ts file like this:

export const GlobalVariable = Object.freeze({
  BASE_API_URL: 'http://www.asdf.com/'
});

And then i have to import it in every component:

import { GlobalVariable } from '../shared/global';

Then i can use "GlobalVariable.BASE_API_URL" in those components. There are two problems with it i dont like. First the part that i have to import it in every single component, is it possible to do a import for all components once? But actually thats a problem i can live with. The bigger problem is that i can seem to access that variable in my html files. Is there a solution for this?

like image 645
user1985273 Avatar asked Jun 19 '17 19:06

user1985273


People also ask

Can we create a global variable in angular?

We always need to declare global variable file for our angular 8 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.

Can global variables be accessed anywhere?

Variables that are created outside of a function are known as Global Variables . A global variable is one that can be accessed anywhere . This means, global variable can be accessed inside or outside of the function.


1 Answers

You can to some extent, yes. You can create a service, define a property in that service, and then you can access that property from any component or any template ... as long as the service is injected into the component.

Service:

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  serviceData: string; 
}

Component/template:

import { Component } from '@angular/core'
import { DataService } from './data.service';

@Component({ 
 template: ` 
  <div> 
    <h2>Data: {{ dataService.serviceData }} </h2> 
  </div> 
  `
})


export class A {

  constructor(public dataService: DataService) {
     console.log(dataService.serviceData);
  } 
}

But notice that you do need to import the service with the imports statement and inject the service using the constructor in every component that needs it.

like image 121
DeborahK Avatar answered Oct 13 '22 03:10

DeborahK