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?
解决方案
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: `
Data: {{ dataService.serviceData }}
`
})
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.