Zerg Zerg - 1 month ago 18
TypeScript Question

Define global variable with Typescript Angularjs in components

My application uses components and boostrapper. I want to create a datepicker which will set a global date variable. I have tried to create a service, use the rootscope and basically all the solutions I could find on stackoverflow but it doesn't seem to work.

What would be the correct approach to create a global variable shared across all components?

Answer

It's generally not a great idea to use a global variable to store state like this, as it's hard to track what is mutating it.

Assuming Angular 1.x, to share information like this, you can simply create a service which stores whatever data you are tracking. I'll add the disclaimer here that state management in web apps is still a tricky problem. You could go for a Redux styled approach, but I'll keep it basic for now.

angular
  .module('app', [])
  .controller('testController', function(testService) {
    console.log(testService.getDate());
  });


angular.module('app')
  .service('testService', function() {
    var date = new Date();

    function getDate() {
      return date;
    }

    function setDate(newDate) {
      date = newDate;
    }
});

This way, you have an interface to read/mutate the date. You can inject it into as many controllers/components as you like.

Hope that helps (I'm aware the answer isn't in Typescript, but I assume since the problem has a basic solution, it doesn't matter too much - if you want a Typescript answer, let me know and I'll change it for you :) ).

Comments