Visible constant throughout the application

Asked

Viewed 257 times

3

Hello, I’m developing the frontend for a API that I developed and I have a little problem, the URL of my API I am defining in all modules I use, I would like to create a global constant for the application to set the URL API and use in all modules.

Can anyone tell me if that’s possible, and if it is, could you show me some example of this?

Thank you.

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 (by the way, MUST) use a constant to this end, provided 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, you should do the Constant injection, 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 declared other variables such as title and default error message, just so you know that you can use this way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.