Constant visible throughout the application

3
Hello, I'm developing the frontend for a API I've developed and I'm having a small problem, the URL of my API I'm setting in all the modules I use, to create a global constant for the application to set URL of the API and use in all modules.

Can anyone tell me if this is possible, and if so, could you show me some example of this?

Thank you.

    
asked by anonymous 14.06.2016 / 12:55

1 answer

4

There are some methods, such as the use of $rootScope (which is the most common and also the worst) that creates a global variable.

But you can also (in fact, MUST) use a constant for this purpose, as long as you are sure that the variable will never change, which is your case.

In this file you can define not only one, but several variables to be accessed later. See the example:

var app = angular.module('app', []);

app.constant('minhaConstant', {
    url: 'meu/caminho/arquivo.php',
    error: 'Algo deu errado, tente novamente',
    title: 'Meu Título'
});

And when you need to use it, you should do the constant injection, just like any other case, see:

app.controller('mainController', function(minhaConstant, $scope, $http){
    $scope.title = minhaConstant.title;

    $http.get(minhaConstant.url).then(function(response){
        console.log(response.data);
    });
})

In the example I will declare other variables, such as title and standard error message, just so you know you can use it this way.

    
14.06.2016 / 13:04