I'm working on an AngularJS project where there is a .constant() provider to declare some basic information used across the whole project. For example, a definition of cookie name. Ex.:
.constant('appConst', {
cookie: 'CookieName',
...
});
But the same thing can be done by declaring a const, ex.:
const appConst = {
cookie: 'CookieName',
...
}
So, what is the advatage of using the .constant provider instead of just declaring a const? I know one of the reasons is because we don't expect the value to change. But isn't this the same objective of a const?
The new const keyword only makes it so you cannot reassign the variable, it doesn't make any object you initially assign to it immutable. So in your example with:
const appConst = {
cookie: 'CookieName',
...
}
You would still be able to change the value of cookie. You just wouldn't be allowed to do something like this:
appConst = { // My new object };
The values in the angular .constant() can also still be changed, so they're not constant in the common use of the word "constant". At least not when you use it like this:
.constant('appConst', {
cookie: 'CookieName',
...
});
So if you for instance do like this and change the value within a controller
app.controller('myController', function(appConst){
appConst.cookie = 'NewCookieName';
})
the change would be reflected anywhere you inject appConst after this controller was constructed.
You can't "reassign" appConst in this case though, that action would just be ignored, so it is constant in that sense.
1- const is new in ES6, so you may need to transpiler your code for supporting old browsers.
2- const is block-scoped, so within a scenario, you define a constant in A.js, will be not able to use it at B.js unless you're using a module bundler, so we went back to the topic 1-.
The main purpose of AngularJS having this native is to able you to share it between controllers, services, and directives, using its dependency injection system.
Related
Good Morning, I explain my scenario:
After generating a couple of http calls and after processing them I have a result similar to this:
xxx.component.ts
nameVariable: any = {};
this.nameVariable = this.createMyObject(params);
console.log(this.nameVariable);
Thanks to the console.log() we can see that is an Object: nameVariable like this:
Object: {
information1: Object {...},
information2: Array [...],
information3: Object{...},
information4: Array[...]
}
How can I save this Object??,
how do I Save it and then be able to use it within the code and/or use it within a Component??
Should use a Model?? what should I study to better understand this thing??
Your angular component is a class. The scope of your nameVariable variable is the body of the method where it is defined. You can extend the scope of that variable by introducing it as a field of your class before the constructor of the class as follows:
nameVariable: { (state here the type of the object };
and you may add a prefix like private or public just before the nameVariable word.
Refer to it as this.nameVariable afterwards inside the methods (the const keyword is no more required).
I would like to share a common url between different components in vuejs
So in my main.js
Vue.prototype.$apiurl = '127.0.0.1:8000/api'
Now in my component i would like to call
console.log("apiurl is", this.$apiurl );
The above doesnt work. How do access global variables in vuejs
Having a dictionary for keeping constants seems more appropriate to me in this case, something like this:
APP_CONSTS = {
API_URL: "127.0.0.1:8000/api"
}
Then accessing it whenever you need, like APP_CONSTS.API_URL.
In some situations you may need to share data between components, in these cases state management comes into play. But it may be an overkill for your case.
I'm looking for a pattern in order to have globals constant in my application. But not with a controller or a factory. (so not with app.constant() too)
I just want to set a variable but I didn't find something good.
I wanted to set this var in my rootScoop but without success.
with something like
myApp.run(function($rootScoop){
$rootScoop.global = {};
});
When I use that code, an arror occurs for nothing (transtateFilterProvider). When I delete this code, the translateService works,
I MUST have access in all html view, I don't want to always use a controller (useless in this case), I just want to set a global variable in rootScoop.
Thank you.
You are getting an error because it is :
$rootScope
And not
$rootScoop
Anyway, correct way to do this is to add a constant module to your app like :
angular.module('yourapp', []).constant('Constants', {
foo: 'bar'
});
But you'll have to call Constants in controllers.
If you use $rootScope, remember you will need to call $root.global in templates.
I have inherited an express application. In the application we pass to res.render a massive list of local variables. For every page we pass about 30 variables that do not change. If one does change it needs to be changed in a dozen places. This is obviously bad.
So what I want to do store the values locals that do not change separate from the truly local. So I placed these non-changing values in their own file and load the file at the start of each route, like so:
'use strict';
var locals =
{
indexName: 'Home',
...lots more of these...
};
module.exports = { locals : locals };
// in each route files
var local = require('../locals.js');
And I can use it via res.render('sensor', local.locals);
However I also need to add page specific values. So I tried local.locals + { ... }; which doesn't while it doesn't give an error doesn't even show the original values.
I then tried local.locals.concat({...}) but that does give an error (TypeError: Object #<Object> has no method 'concat'), likewise for extend and push.
Is there no methods to extend or merge two objects? Do I need to roll my own?
Also, is this the best way of making the an array global? I would prefer just to call it locals, and not local.locals as that is just cumbersome.
In addition to Object.assign from #mostruash, there are two JS libraries that are very similar, which both provide an object merge function (along with a lot of nice helper utilities). Pick one:
underscore
lodash
Edit: and as to your second question about local.locals...of course, just export the object itself, rather than an object that wraps it:
module.exports = locals;
...and in your routes:
var locals = require('../locals');
console.log(locals.indexName);
When creating an Angular Module one could essentially add global arrays or objects to the module. Like so..
var myApp = angular.module('myApp', ['myModule']);
myApp.run(function()
{
});
angular.module('myModule', [])
.run(function()
{
// global to module
var thisModule = angular.module('myModule');
thisModule.globalArray = [];
thisModule.globalObject = {};
});
So here's the question(s). Would it be a bad idea to do something like this? Is there anything in the documentation that recommends not doing this? And if so, why would or wouldn't you recommend not doing this?
Demo:
http://jsfiddle.net/hrpvkmaj/8/
In general, Angular goes to great lengths to avoid global state. You can observe this in the dependency injection system that the framework is based on. To use a component, you must inject it as a parameter that is wired up behind the scenes. The framework also has a powerful scoping system that allows for nice and easy encapsulation. Relying on global variables works against these systems.
In particular, it would be a bad idea to do something exactly like your code example because it isn't how Angular was designed to be used. You shouldn't be adding your own properties to Angular's module object. At the very least, you should be injecting the $rootScope object and adding your global variables to that.
app.run(function($rootScope)
{
$rootScope.globalArray = [];
$rootScope.globalObject = {};
});
From the Angular documentation:
Every application has a single root scope. All other scopes are descendant scopes of the root scope.
If you went this route, you could inject $rootScope wherever you need to use those global values.
However, the Angular team discourages using $rootScope.
Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.
There is another way of defining global values in Angular that is even preferable over using $rootScope: defining a value provider.
A value provider is the simplest kind of provider. It defines a single value that can be injected throughout your app.
You can define one like this:
app.value("myValue", {
someProp: 'Hello World'
});
Then you can inject the value wherever you need it like this:
app.controller("myController", function ($scope, myValue) {
$scope.someValue = myValue.someProp;
});
Here's a fiddle using a value provider to inject a global value.
In the end, any answer you get, including this one, will include some level of subjectivity. There are many ways to handle global values, but Angular provides some really convenient ways of using the framework to accomplish this.