Using angular-translate's $translate.use() in the ui-router config file - javascript

I'm trying to use $translate.use() in my ui-router config file routes.js so I can switch toggle language with a state but I get an
Uncaught Error: [$injector:modulerr] Failed to instantiate module frontApp due to:
Error: [$injector:unpr] Unknown provider: $translate
Here is my file.
'use strict';
(function() {
angular.module('frontApp')
.run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}]
)
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', '$translate', function($urlRouterProvider, $stateProvider, $locationProvider, $translate){
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/views/home.html',
controller: 'HomeCtrl'
})
.state('home.rules', {
url: '^/rules',
templateUrl: '/views/rules.html'
})
.state('home.terms', {
url: '^/terms',
templateUrl: '/views/terms.html'
})
.state('home.faq', {
url: '^/faq',
templateUrl: '/views/faq.html'
})
.state('language', {
controller: function() {
console.log('ok');
$translate.use(($translate.use() === 'fr') ? 'en' : 'fr' );
}
});
$locationProvider.html5Mode(true);
}]);
}());
I also have a translation.js file containing my translations and when not trying to inject and use $translate.use() in the above routes.js file I have no problem using it using the TranslateController:
'use strict';
(function() {
angular.module('frontApp')
.config(['$translateProvider', function($translateProvider) {
$translateProvider
.translations('fr', {
language: 'English',
otherLanguage: 'en',
cssClass: 'french',
linkHome: 'Accueil',
linkRules: 'Règlement',
linkTerms: 'Termes et conditions',
linkFAQ: 'FAQ',
})
.translations('en', {
language: 'Français',
otherLanguage: 'fr',
cssClass: 'english',
linkHome: 'Home',
linkRules: 'Rules',
linkTerms: 'Terms and conditions',
linkFAQ: 'FAQ',
});
$translateProvider.preferredLanguage('fr');
}])
.controller('TranslateController', ['$translate', '$scope', '$location', function ($translate, $scope, $location) {
// The URLs need to be updated
var host = $location.host();
if ( host === 'localhost' || host === '0.0.0.0') {
$translate.use('fr');
}
else if (host === 'localhost-en') {
$translate.use('en');
}
$scope.switchLanguage = function() {
$translate.use(($translate.use() === 'fr') ? 'en' : 'fr' );
};
}]);
}());
Here is the app.js:
'use strict';
angular
.module('frontApp', [
'ui.router',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'pascalprecht.translate'
]);
What am I missing ? Many thanks for your time and help.

Solution here would be to move the DI definition of the '$translate' - where it belongs, i.e. into controller definition:
.state('language', {
// instead of this
// controller: function() {
// use this
controller: function($translate) {
console.log('ok');
$translate.use(($translate.use() === 'fr') ? 'en' : 'fr' );
}
});
or even better controller: ['$translate', function($translate) {... }]
Why is current solution not working? Well, let's have a look at this extract from the above code:
// I. CONFIG phase
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', '$translate'
, function($urlRouterProvider, $stateProvider, $locationProvider, $translate){
...
$stateProvider
...
.state('language', {
// II. CONTROLLER - RUN phase
controller: function() {
As we can see, we ask for $translate above in the config phase. So we recieve the provider... to be configured.
But the controller definition is expecting to be provided with a servic - already configured. It must have its own DI ... because it will be executed in a RUN phase...
Also check this Q & A for more details about provider in config vs run phase - Getting Error: Unkown provider: $urlMatcherFactory

Related

Can pass login page with wrong password/username AngularJS

If type the username or password once wrong and change manually the URL to my home GUI, I get access to it without any authentication.
I can't explain why :/
this is my app.js, where all the routing happens and a fiddle with my controller and my html data :
(function() {
'use strict';
// declare modules
angular.module('Authentication', []);
angular.module('Home', ['naif.base64', 'ngFileSaver']);
//dependecies of the module
angular.module('JMeterGui', ['Authentication','Home','ngRoute', 'ngCookies'])
//configure the module
.config(config)
//configure the start of the module
.run(run);
//dependencies of the config module
config.$inject = ['$routeProvider', '$locationProvider', '$qProvider'];
//configure routing depends on the actual URL
function config($routeProvider, $locationProvider, $qProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html'
})
.otherwise({ redirectTo: '/login' });
}
//dependecies of the run module
run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookies.getObject('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in
var restrictedPage = $.inArray($location.path(), ['/login']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})()
my fiddle with controller and html
Anyone knows why ?
Try to add:
if (restrictedPage && !loggedIn) {
//Prevent default
event.preventDefault();
$location.path('/login');
}

Cannot read property 'defaults' of undefined when trying to add token inside stateChangeStart

My objective is to to send a token as Authorization header to each of the service calls in my application.
Here is my code
'use strict';
var properties = {};
angular.module('nbaportalUi', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize',
'ngResource', 'ui.router', 'ui.bootstrap', 'uiSwitch'])
.run(['$rootScope', '$state', '$window', '$cookies', function ($rootScope, $state, $window, $cookies, $http) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
$http.defaults.headers.common.Authorization = 'Bearer carmeloanthony' ;
});
}])
.config( function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider
.otherwise('/home');
// note the 'abstract:true' state below - it can not get activated
// it is activated implicitly when one of its descendants are activated
$stateProvider
.state('app', {
abstract: true,
controller: 'MainCtrl',
templateUrl: 'app/main/main.html'
})
.state('app.overview', {
url: '/overview',
templateUrl: 'app/overview/summary.html',
controller: 'OverviewCtrl'
})
.state('loginPage', {
url: '/login',
templateUrl: 'app/login/login.html',
controller: 'LoginCtrl'
})
.state('errorPage', {
url: '/error404',
templateUrl: 'app/404.html'
});
})
.constant('ENV', {
'name': 'dev',
'apiEndpoint': 'https://api.blah.com/nba/v1/team/'
})
;
I am inserting $http.defaults.headers.common.Authorization = 'Bearer carmeloanthony' ; inside $stateChangeStart because it is called every time.
However when i attempt to this i get an error saying
angular.js:11706 TypeError: Cannot read property 'defaults' of undefined
at index.js:43
This error is refering to the following line of code -> $http.defaults.headers.common.Authorization = 'Bearer carmeloanthony' ;
However when i try to add the token as authorization adder outside stateChangeStart as follows it works:
'use strict';
var properties = {};
angular.module('nbaportalUi', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize',
'ngResource', 'ui.router', 'ui.bootstrap', 'uiSwitch'])
.run(['$rootScope', '$state', '$window', '$cookies', function ($rootScope, $state, $window, $cookies) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
});
}])
.config( function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider
.otherwise('/home');
// note the 'abstract:true' state below - it can not get activated
// it is activated implicitly when one of its descendants are activated
$stateProvider
.state('app', {
abstract: true,
controller: 'MainCtrl',
templateUrl: 'app/main/main.html'
})
.state('app.overview', {
url: '/overview',
templateUrl: 'app/overview/summary.html',
controller: 'OverviewCtrl'
})
.state('loginPage', {
url: '/login',
templateUrl: 'app/login/login.html',
controller: 'LoginCtrl'
})
.state('errorPage', {
url: '/error404',
templateUrl: 'app/404.html'
});
})
.constant('ENV', {
'name': 'dev',
'apiEndpoint': 'https://api.blah.com/nba/v1/team/'
})
;
angular.module('nbaportalUi').run(function($http) {
$http.defaults.headers.common.Authorization = 'Bearer carmeloanthony' ;
});
I would prefer to get my first approach working. I appreciate any help I can get.
You have to include the $http service as following (your forgot to put in the array) :
.run(['$rootScope', '$state', '$window', '$cookies','$http', function ($rootScope, $state, $window, $cookies, $http) {

ui-router - $state.go() not working

Here is the app.js of my project:
(function () {
'use strict';
angular
.module('app', ['ui.router', 'ngCookies', 'angular-inview', 'ngMaterial'])
.config(config)
.run(run);
config.$inject = ['$stateProvider', '$urlRouterProvider', '$mdThemingProvider'];
function config($stateProvider, $urlRouterProvider, $mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('deep-orange')
.accentPalette('teal', {
'default': 'A400'
});
$urlRouterProvider.otherwise('/app');
$stateProvider
.state('app', {
url: '/app',
data: {
clearenceLevel: 1
},
views: {
'': {
templateUrl: 'app/views/navbar.html',
}
}
})
.state('home.works', {
url: '/works',
templateUrl: 'app/views/works.html',
controller: 'WorksController as vm'
})
.state('login', {
url: '/login',
templateUrl: 'app/views/login.html',
controller: 'LoginController as vm',
data: {
clearenceLevel: 0
}
})
.state('register', {
url: '/register',
templateUrl: 'app/views/register.html',
controller: 'RegisterController as vm',
data: {
clearenceLevel: 0
}
});
}
run.$inject = ['$rootScope', '$location', '$state', '$cookieStore', '$http', 'AuthenticationService'];
function run($rootScope, $location, $state, $cookieStore, $http, AuthenticationService) {
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['aimm-token'] = $rootScope.globals.currentUser.token;
$http.defaults.headers.common['aimm-id'] = $rootScope.globals.currentUser.id;
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
var clearenceLevel = toState.data.clearenceLevel;
var loggedIn = $rootScope.globals.currentUser;
if (clearenceLevel > 0 && !loggedIn) {
alert("redirecting");
return $state.go('login');
}
});
}
})();
I just can't have $state.go() working. The $on('$stateChangeStart'...); is working fine, and the alert is poping when trying to reach a protected state with no session. But the return $state.go('login'); doesnt work. It redirects to /app.
Thanks for your help.
Well, thanks to #Vanojx1, I found out adding e.preventDefault(); before the $state.go('login'); made it work. Still dont understand why though.
You need to execute the $state.go on main scope and not in a (angular) service or virtual scope created temporarily.
You can also solve the problem by wrapping it in $timeout or setTimeout which will register it in the browser loop to be executed after the current method run etc even with 0 milliseconds will do it, like.
$timeout(()=>{$state.go('xyz')},0)
or
setTimeout(()=>{$state.go('xyz')},0);

Angularjs Restful using ngResource not working

I am trying to expose restful web service using angularjs ngResource using java as my backend everything seems to be correct but don't know What is wrong with my code
nothing gets displayed in browser help me with this
service.js
'use strict';
var employeeServices = angular.module('myApp.services',['ngResource']);
employeeServices.factory('Employees',['$resource',function ($resource){
return $resource('my service link', {},{
query:{method:'GET',isArray:true}
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers',[]).
controller('Myctrl1',['$scope','Employees',function ($scope ,Employees){
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2',[function (){
}]);
app.js
'use strict';
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1',{templateUrl:'partials/partials.html',controller:'Myctrl1'});
$routeProvider.when('/view2',{templateUrl:'partials/partials1.html',controller:'Myctrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
If you want to use service of one module in another module you have to inject it.
service.js
'use strict';
var employeeServices = angular.module('myApp.services', ['ngResource']);
employeeServices.factory('Employees', ['$resource', function ($resource) {
return $resource('my service link', {}, {
query: { method: 'GET', isArray: true }
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers', ['myApp.services']).
controller('Myctrl1', ['$scope', 'Employees', function ($scope, Employees) {
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2', [function () {
}]);
app.js
'use strict';`enter code here`
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view1', { templateUrl: 'partials/partials.html', controller: 'Myctrl1' });
$routeProvider.when('/view2', { templateUrl: 'partials/partials1.html', controller: 'Myctrl2' });
$routeProvider.otherwise({ redirectTo: '/view1' });
}]);
try this

Yeoman: AngularJS & facebook SDK, page not loading

So im new with Angular and i downloaded the Yeoman scaffolding for Angular.JS to fiddle with it a bit.
I'm trying to implement Facebook Login with this library: https://github.com/pc035860/angular-easyfb
Nothing is loading and the console doesnt reflect anything. I'm almost sure the problem has something to do with the injecting of the facebook dependency on the controller.
I have this on my main.js file:
angular.module('circeApp', ['ezfb'])
.controller('MainCtrl', function($scope, ezfb, $window, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function(){
ezfb.login(function(response){
if(response.authResponse){
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes'});
};
$scope.logout = function(){
ezfb.logout(function(){
updateLoginStatus(updateApiMe);
});
};
function updateLoginStatus(more){
ezfb.getLoginStatus(function(response){
$scope.loginStatus = response;
(more || anular.noop)();
});
}
function updateApiMe(){
ezfb.api('/me', function(response){
$scope.apiMe = response;
});
}
});
And this on my app.js file:
'use strict';
angular.module('circeApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ezfb'
])
.config(function ($routeProvider, $locationProvider, $httpProvider, ezfbProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'partials/login',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'partials/signup',
controller: 'SignupCtrl'
})
.when('/settings', {
templateUrl: 'partials/settings',
controller: 'SettingsCtrl',
authenticate: true
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
// Intercept 401s and redirect you to login
$httpProvider.interceptors.push(['$q', '$location', function($q, $location) {
return {
'responseError': function(response) {
if(response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
}]);
})
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$routeChangeStart', function (event, next) {
if (next.authenticate && !Auth.isLoggedIn()) {
$location.path('/login');
}
});
//Configure ezfb provider aqui
ezfbProvider.setInitParams({
appId: 'XXXXXXXXXXXX',
status: true,
cookie: true,
xfbml: true
});
});
Before this, the page rendered but console told me: "Argument 'MainCtrl' is not a function, got undefined". I fixed a missing parenthesis and made sure ezfb was included in angular.module. Now, the only thing i get is a blank page.

Categories

Resources