AngularJS - Everything depends on my login service? - javascript

New to Angular here.
I've created a login service, such that when a user logs in, I store things like user name, email, ID, profile picture, etc. within a hash.
Other controllers, can retrieve this information by adding a dependency for this login service, and then accessing the correct property. Example
function MyController(loginservice) {
this.getUsername = function() {
return loginService.userData.userName;
}
this.getUserId = function() {
return loginService.userData.userId;
}
this.getProfilePictureUrl = function() {
return loginService.userData.profilePictureUrl;
}
}
And this works fine... However pretty much every directive and every component and every page is now depending on the loginservice, because they need that info in some form or another.
I suppose an alternative approach is to make the components themselves agnostic of the loginservice, and simply pass the required data as attributes. E.g.
<my-directive username="myController.getUsername()" userId="myController.getUserId()">
</my-directive>
<my-profile picturePath="myControllere.getProfilePicUrl()" username="myController.getUsername()" userId="myController.getUserId()">
</my-directive>
However, this seems a bit overkill.
Any thoughts here?

You are really overcomplicating things by making functions and element attributes for each property of the userData.
If you need the userData in controller just assign the whole object once. Then in view you can add the applicable properties needed to display
In controller or directive:
this.user = loginService.userData
In view:
My Name is {{myController.user.userName}}
<img ng-src="{{myController.user.profilePictureUrl}}">
Or:
<my-directive user="myController.user"></my-directive>
As noted above in comments you can easily inject the user service into the directive also and avoid having to create the same scope item in controller and directive attributes and then in directive scope.
Additionally none of those getter functions you have would be created in the controller, rather they would be in the service so they would also be made available to other components. The structure shown in question is backwards
For example from your current controller code:
this.getUserId = function() {
return loginService.userData.userId;
}
Should really look more like:
this.userId = loginService.getUserId();//method defined in service

I've got a similar setup. I'd recommend using ui-router resolutions, which you can then use to resolve dependencies like user data at the parent, then access in child controllers and views.
There are two key points here:
1) To access 'user' data in child views, you can simply reference the object in parent scope.
2) To access 'user' data in child controllers, you can inject the resolve object.
Here's my setup. This is an example of scenario 1 - accessing data from a child view:
// the root state with core dependencies for injection in child states
.state('root', {
url: "/",
templateUrl: "components/common/nav/nav.html",
controller: "NavigationController as nav",
resolve: {
user: ['user_service', '$state', '$mixpanel',
function(user_service, $state, $mixpanel) {
return user_service.getProfile()
.success(function(response) {
if (response.message) {
$state.go('logout', { message: String(response.message) });
}
if (response.key) {
$mixpanel.people.set({
"$name": response.profile.name,
"$email": response.profile.email
});
}
})
.error(function(response) {
$state.go('logout', { message: String(response.message) });
});
}]
}
})
In my NavigationController, I can define scope to allow child views to access 'user' like so:
function NavigationController($auth, user) {
if ($auth.isAuthenticated()) {
this.user = user.data; // reference 'this' by using 'nav' from 'NavigationController as nav' declaration in the config state - * nav.user is also usable in child views *
}
}
Then you specify the 'root' state as the parent, such as:
.state('welcome', {
parent: "root",
url: "^/welcome?invite_code",
templateUrl: "components/common/welcome/welcome.html",
controller: "WelcomeController as welcome"
})
As for scenario 2, injecting 'user' into a controller, now that the 'welcome' state is a child of the 'root' state, I can inject 'user' into my WelcomeController:
function WelcomeController(user) {
var user_profile = user.data;
}

Related

HTML redirect to AngularJS controller with parameters

I inherited a mess. And I need a quick fix for some code that needs to be completely rewritten - but not enough time to do a complete rewrite yet.
Orig developer created an index.js file that has all kinds of global functions used all through an AngularJS/Ionic project. Quite often I am finding AngularJS functions in specific controllers actually passing $scope/$q out to the standard JS functions in the index.js file - its a mess.
One of these global functions is window.FirebasePlugin.onNotificationOpen - which is watching for any inbound pushNotification/messages. The original developer was simply using an "alert" for inbound messages with a data payload. We are now trying to redirect those messages to open up in proper popover or modal windows that belong in the controller in two specific pages.
So the question is, in the global watch JS function, how can I direct
the 'data/payload' to a controller to process in a proper $scope?
I have modified the .state to accept parameters - and then all the subsequent code is in place to pass the $stateParams into specific controllers:
.state('tab.clubs', {
cache: true,
url: '/clubs',
views: {
'tab-clubs': {
templateUrl: 'templates/tab-clubs.html',
controller: 'ClubCtrl',
params: {
'pushAction' : 0,
'pushCode' : 'default'
}
}
}
})
The problem I am having is trying to figure out how to pass URL data from standard JS into the AngularJS .state
The global JS function:
window.FirebasePlugin.onNotificationOpen(function(payload) {
// if there is a payload it will be in payload object
if (payload.action == 1) {
window.location("/clubs/", payload) ; // process message in ClubCtrl
} else if (payload.action == 2) {
window.location("/map/", payload) ; // process message in MapCtrl
}
}, function(error) {
console.error(error);
}) ;
But this method fails.
If your not going to use angulars router to navigate to the page you will need to declare the params in the URL somehow. You can use path params by doing something like /clubs/:pushAction/:pushCode or url params with something like /clubs?pushAction&pushCode
Example:
.state('tab.clubs', {
cache: true,
url: '/clubs/:pushAction/:pushCode',
views: {
'tab-clubs': {
templateUrl: 'templates/tab-clubs.html',
controller: 'ClubCtrl',
params: {
'pushAction' : 0,
'pushCode' : 'default'
}
}
}
})
Then navigate it with
location.href = `/clubs/${payload.action}/${payload.code}`
Additionally if you have alot of unknown params you could also pass in the whole payload as base64 encoded json. I wouldnt recommend this but it is... a solution
.state('tab.clubs', {
cache: true,
url: '/clubs?state',
views: {
'tab-clubs': {
templateUrl: 'templates/tab-clubs.html',
controller: 'ClubCtrl',
params: {
'state' : 0,
}
}
}
})
window.location(`/clubs?state=${btoa(JSON.stringify(payload))}`
Then in your controller reverse that operation
class ClubCtrl {
...
// parses the state out of the state params and gives you the full payload
parseState($stateParams) {
return JSON.parse(atob($stateParams.state));
}
...
}
It would give you all the payload, but its pretty gross

$onChanges not triggered

Get updated by model but don't update the model. Should I use the $onChanges function
I have a model:
class Model {
constructor(data) {
this.data = data;
}
getData() {
return this;
}
}
2 nested components:
var parentComponent = {
bindings: {
vm: '<'
},
controller: function() {
var ctrl = this;
},
template: `
<div>
<a ui-sref="hello.about" ui-sref-active="active">sub-view</a>
Parent component<input ng-model="$ctrl.vm.data">
<ui-view></ui-view>
</div>
`
};
var childComponent = {
bindings: {
vm: '<'
},
template: `
<div>
Child component <input ng-model="$ctrl.vm.data">
<br/>
Child component copy<input ng-model="$ctrl.vmCopy.data">
<br/>
Child component doCheck<input ng-model="$ctrl.vmCheck.data">
</div>
`,
controller: function() {
var ctrl = this;
ctrl.$onChanges = function(changes) {
ctrl.vmCopy = angular.copy(ctrl.vm);
ctrl.vm = ctrl.vm;
};
ctrl.$doCheck = function () {
var oldVm;
if (!angular.equals(oldVm, ctrl.vm)) {
oldVm = angular.copy(ctrl.vm);
ctrl.vmCheck = oldVm;
console.log(ctrl)
}
}
}
}
Both get data from resolve:
.config(function($stateProvider) {
var helloState = {
name: 'hello',
url: '/hello',
resolve: {
vm: [function() {
return myModel.getData();
}]
},
component: 'parent'
}
var aboutState = {
name: 'hello.about',
url: '/about',
resolve: {
vm: [function() {
return myModel.getData();
}]
},
component: 'child'
}
$stateProvider.state(helloState);
$stateProvider.state(aboutState);
})
I would like my components to be updated when model change or when parent change, but I don't wan't them to update the model.
I thought that was why one way binding '<' stands for.
Here's a fiddle to illustrate what I want to do.
In other word:
I would like the child component to be updated on parent changes but don't want the child to update the parent.
You can see in the fiddle that if I bind directly to local scope, child get update from parent but also update the parent
If I copy the binding to local scope, child isn't updating the parent but also doesn't get updated by parent.
If
With object content — Use the $doCheck Life-cycle Hook1
When binding an object or array reference, the $onChanges hook only executes when the value of the reference changes. To check for changes to the contents of the object or array, use the $doCheck life-cycle hook:
app.component('nvPersonalTodo', {
bindings: {
todos: "<"
},
controller: function(){
var vm = this;
this.$doCheck = function () {
var oldTodos;
if (!angular.equals(oldTodos, vm.todos)) {
oldTodos = angular.copy(vm.todos);
console.log("new content");
//more code here
};
}
})
From the Docs:
The controller can provide the following methods that act as life-cycle hooks:
$doCheck() - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when $onChanges is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by Angular's change detector and thus not trigger $onChanges. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.
— AngularJS Comprehensive Directive API Reference -- Life-cycle hooks
For more information,
AngularJS angular.equals API Reference
AngularJS 1.5+ Components do not support Watchers, what is the work around?

Configure ui-router with components containing multiple bindings

I am trying to find a better solution to use the ui-router together with angular components.
Consider two simple components:
app.component('componentOne', {
template: '<h1>My name is {{$ctrl.name}}, I am {{$ctrl.age}} years old.</h1>',
bindings : {
name : '#',
age : '#'
}
}
);
app.component('componentTwo', {
template: '<h1>I am component 2</h1>'
});
Right now, I am specifying the component and its parameter using the template property:
app.config(function($stateProvider, $urlRouterProvider ){
$stateProvider
.state('component1', {
url: "/component1",
template: "<component-one name=\"foo\" age=\"40\"></component-one>"
})
.state('component2', {
url: "/component2",
template: "<component-two></component-two>"
})
});
While this is working fine, I have components with arround ten bindings which makes the configuration of the ui-router realy awkward.
I tried using the component property but this doesn't work for me at all. The only other solution I found is to specify the parent using the require property and omit the bindings - but this doesn't feel right for me... Is there a better way to do this?
Here is a plnkr.
UI-Router component: routing exists in UI-Router 1.0+ (currently at 1.0.0-beta.1)
Here's an updated plunker: https://plnkr.co/edit/VwhnAvE7uNnvCkrrZ72z?p=preview
Bind static values
To bind static data to a component, use component and a resolve block which returns static data.
$stateProvider.state('component1', {
url: "/component1",
component: 'componentOne',
resolve: { name: () => 'foo', age: () => 40 }
})
Bind async values
To bind async values, use a resolve which returns promises for data. Note that one resolve can depend on a different resolve:
$stateProvider.state('component1Async', {
url: "/component1Async",
component: "componentOne",
resolve: {
data: ($http) => $http.get('asyncFooData.json').then(resp => resp.data),
name: (data) => data.name,
age: (data) => data.age
}
});
Bind lots of values
You mention you have 10 bindings on a component. Depending on the structure of the data you're binding, you can use JavaScript to construct the resolve block (it's "just javascript" after all)
var component2State = {
name: 'component2',
url: '/component2',
component: 'componentTwo',
resolve: {
data: ($http) => $http.get('asyncBarData.json').then(resp => resp.data)
}
}
function addResolve(key) {
component2State.resolve[key] = ((data) => data[key]);
}
['foo', 'bar', 'baz', 'qux', 'quux'].forEach(addResolve);
$stateProvider.state(component2State);
Alternatively, you can move your bindings a level down and create an object which will be the only bindings. If 10 bindings is what is bothering you.
One alternative you can try is to override the template by custom properties of states in $stateChangeStart event.
Run block like this to achieve this kind of behaviour.
app.run(function($rootScope){
//listen to $stateChangeStart
$rootScope.$on("$stateChangeStart",function(event, toState, toParams, fromState, fromParams, options){
//if the component attribute is set, override the template
if(toState.component){
//create element based on the component name
var ele = angular.element(document.createElement(camelCaseToDash(toState.component)));
//if there is any binding, add them to the element's attributes.
if(toState.componentBindings){
angular.forEach(toState.componentBindings,function(value,key){
ele.attr(key,value)
})
}
//you may also do something like getting bindings from toParams here
//override the template of state
toState.template = ele[0].outerHTML;
}
})
//convert camel case string to dash case
function camelCaseToDash(name) {
return name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
})
And with this now you can have component property in your state config.
app.config(function($stateProvider, $urlRouterProvider ){
$stateProvider
.state('component1', {
url: "/component1",
component:"componentOne",
componentBindings:{
name:"foo",
age:"40",
}
})
.state('component2', {
url: "/component2",
component:"componentTwo",
})
});
Here is the working plunker.
Still you may have a large config function, but it will look not so awkward.

how to bind the relevant value in case of current status in ui-router?

I have attached data attribute in each .state to identify the user (authenticated or public) as following (one state example)
$stateProvider
.state('admin-panel.public.home', {
url: '/p',
templateUrl: 'app/public/home.tmpl.html',
controller: 'PublicHomeController',
controllerAs: 'ctrl',
data: {
requireLogin: false
}
});
I need to use the some state for both of user (authenticated and public) as an example
.state('403', {
url: '/403',
templateUrl: '403.tmpl.html',
controller: function($scope, $state, APP, Auth) {
$scope.app = APP;
$scope.goHome = function() {
if(Auth.isAuthenticated()){
$scope.requireLogin = true;
$state.go('admin-panel.default.home');
}
else{
$scope.requireLogin = false;
$state.go('admin-panel.public.home');
}
};
},
data: {
requireLogin: $scope.requireLogin
}
})
Here when the authenticated user access this state I need to pass the true value to requireLogin: true as well when public user access this state I need to pass the false value as requireLogin: false. I checked the current user status in the controller as above. How can I bind the $scope.requireLogin to data attribute?
Anyone in expert of ui-router please tell a way to solve???
You can solve your problem in a very cleaner way. Let's start with a global controller example GlobalCtrl which is added to the body or html tag like ng-controller="GlobalCtrl.
Doing this will enable us to keep the scope of this GlobalCtrl throughout your single page Angular app (as you are using ui-router) and we can avoid the usage of $rootScope (actually mimicking the usage of $rootScope).
Now, inside your GlobalCtrl define something like this:
// Using an object to avoid the scope inheritance problem of Angular
// https://github.com/angular/angular.js/wiki/Understanding-Scopes
$scope.globalData = {};
// Will be called everytime before you start navigating to any state
$scope.$on('$stateChangeStart', function(event, toState, toParams) {
$scope.globalData.requireLogin = false;
var statesToLoginCheck = ['403', 'foo', 'bar']; // and other states on which you want to check if user is logged in or not
// If the current state on which we are navingating is allowed to check for login
if (statesToLoginCheck.indexOf(toState.name) > -1) {
if (Auth.isAuthenticated()) {
$scope.globalData.requireLogin = true;
$state.go('admin-panel.default.home');
} else {
$scope.globalData.requireLogin = false;
$state.go('admin-panel.public.home');
}
event.preventDefault();
return;
}
});
Now, since $scope of GlobalCtrl is in body or html then every state or directive will inherit the scope of this GlobalCtrl and then you simply have to check in your any controller of variable $scope.globalData.requireLogin.

angularjs i18n routing with path params

In one application that I'm working with, the route system need to be integrated with i18n, like the example below:
$routeProvider.when('/:i18n/section', ...);
But I'm facing some issues due to, what I guess it is, the $digest cycle, which doesn't change the i18n param at the runtime.
Other issue that I'm facing is, if the location path is pointed to something like:
http://localhost:9000/section/...
not like:
http://localhost:9000/en/section/...
the i18n path param ends being associated with /section/, which means, on $routeParams service, $routeParams.i18n = 'section';. This is expected, but I need to be able to parse the /:i18n/ param, to avoid this conflicts, and change the URL, concatenating one locale, to contextualize the session, replacing the current route with the new one, i18n-ized, whithout refreshing the view/app automatically, yet selectivelly, because some features only need to be changed, not all.
Also, I've designed one service that evaluates, based on a list of possible language settings and its weights, the language that'll be selected to the current context:
var criteria = {
default: {
tag: 'en',
weight: 10
},
user: {
tag: 'pt',
weight: 20
},
cookie: {
tag: 'zh',
weight: 30
},
url: {
tag: 'ru',
weight: 40
},
runtime: {
tag: 'es',
weight: 50
}
};
function chooseLanguage (languages) {
var deferred = $q.defer();
var weights = [];
var competitors = {};
var choosen = null;
if (defineType(languages) === 'array') {
for (var i = languages.length - 1; i >= 0; i--) {
if (languages[i].tag !== null) {
weights.push(languages[i].weight);
competitors[languages[i].weight] = languages[i];
}
}
choosen = competitors[Math.max.apply(Math, weights)];
} else if (defineType(languages) === 'object') {
choosen = languages;
} else {
return;
}
setRuntimeLanguage(choosen.tag);
deferred.resolve(choosen);
return deferred.promise;
}
Explaining the code above, when angular bootstraps the app, the snippet is executed, selecting which language is defined and if its strong enough to be selected. Other methods are related to this operation, like de detection of the URL param, if there's one logged user, etc, and the process is executed not only on the bootstrap, but on several contexts: $routeChangeStart event, when the user autenticates its session, switching the languages on a select box, and so on.
So, in resume, i need to be able to:
Parse the URL and apply the locale param properly, if its not informed initialy;
Change the URL i18n param during the runtime, whithout reloading the whole view/app;
Deal with the language changes correctly, which means, if my approach based on weights isn't the better way to go, if you suggest me something else.
Edit 1:
A $watcher doesn't do the trick because the app needs the correct locale in every path, even before it instantiates all the elements. AngularJS is used in every step of this check, but if there's any clue to do this outside, before Angular instantiates, we can discuss about it.
For now, I'm using the accepted answer below, with a solution that I developed, but it has to be improved.
I've ended up doing a kind of preliminary parse on the URL. Using only ngRoute (ui-router wasn't an option...), I check if the path matches with the restrictions, if not, a redirect is triggered, defining correctly the path.
Below, follows a snippet of the solution, for the primary route, and a simple subsequent example, due to the quantity of the routes on the app, and their specific data, that doesn't belongs to the basis idea:
$routeProvider
.otherwise({
redirectTo: function () {
return '/404/';
}
})
.when('/:i18n/', {
redirectPath: '/:i18n/',
templateUrl: 'home.html',
controller: 'HomeCtrl',
resolve: {
i18n: [
'$location',
'$route',
'i18nService',
function ($location, $route, i18nService) {
var params = $route.current.params;
return i18nService.init(params.i18n)
.then(null, function (fallback) {
if (params.i18n === '404') {
return $location.path('/' + params.i18n + '/404/').search({}).replace();
}
$location.path('/' + fallback).search({}).replace();
});
}
],
data: [
'dataService',
function (dataService) {
return dataService.resolve();
}
]
}
})
.when('/:i18n/search/:search/', {
redirectPath: '/:i18n/search/:search/',
templateUrl: 'search.html',
controller: 'SearchCtrl',
resolve: {
i18n: [
'$location',
'$route',
'i18nService',
function ($location, $route, i18nService) {
var params = $route.current.params;
return i18nService.init(params.i18n)
.then(null, function (fallback) {
$location.path('/' + fallback + '/search/').search({
search: params.search
}).replace();
});
}
],
data: [
'$route',
'searchService',
function ($route, searchService) {
var params = $route.current.params;
return searchService.resolve({
'search': params.search
});
}
]
}
});
The redirectPath property is used in case of you need the pattern for that route, because ngRoute keeps one copy for private use, but doesn't give access to it with $route public properties.
Due to the required parse before any app request (except the i18nService, which loads the locale list and triggers angular-translate to load the translations), this methods causes several redirects, which leads to a significant delay on the instantiation.
If any improvements are possible, I'll thanks for, also, if I found a better way to do it, I'll update this answer with it.

Categories