angularjs resolve is undefined - angularjs

so in my state, i have
angular.module('app', ['ui.router', 'chart.js'])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/home',
component: 'home',
resolve: {
data: ['$http', function ($http) {
return $http.get('some api call')
.then(function (response) {
console.log("this is the response", response);
return response;
});
}]
}
});
}]);
then i get the proper response back. but when i check my resolve in here,
angular.module('app')
.component('home', {
templateUrl: 'Content/app/components/home.html',
bindings: {
resolve: '<'
},
controller: [
function () {
var vm = this;
vm.$onInit = function () {
console.log("this is the resolve", vm)
}
}]
});
i see that my resolve is undefined. Am i doing something wrong?

$stateProvider will bind what you specify inside the resolve object to your component, rather than binding the whole resolve object itself.
angular.module('app')
.component('home', {
templateUrl: 'Content/app/components/home.html',
bindings: {
data: '<'
},
controller: [
function () {
var vm = this;
vm.$onInit = function () {
console.log("this is the resolve", vm)
}
}]
});
Documentation link: https://ui-router.github.io/ng1/docs/latest/interfaces/state.statedeclaration.html#as-an-object

Related

AngularJS: goto previous url with refresh using $window

I am a newbie of AngularJS using version 1.6.4, What i am trying to do is redirect user on previous page with a complete refresh. Right now i am getting back but page is not refreshing. Any idea how can i do that with a single line code.
user-login.component.js:
(function () {
"use strict";
var module = angular.module(__appName);
function controller(authService, $window, $location, $document) {
var model = this;
model.$onInit = function () {
//TODO:
};
model.login = function () {
authService.login(model.email, model.password).then(function (response) {
//$window.history.back();
//$window.history.go(-1);
//$window.location.href = '/';
console.log("url:"+$document.referrer);
//$document.referrer is showing undefined in console
$location.replace($document.referrer);
},
function (response) {
model.msg = response.error;
});
}
}
module.component("userLogin", {
templateUrl: "components/user-login/user-login.template.html",
bindings: {
email: "<",
password: "<"
},
controllerAs: "model",
controller: ["authService", "$window", "$location", "$document" controller]
});
}());
App.js:
"use strict";
//Global variables
var __apiRoot = "http://localhost:8000/api"; //No slash '/' at the end
var module = angular.module(__appName, [
"ui.router",
"angular-jwt"
]);
module.config(function ($stateProvider, $urlRouterProvider, $httpProvider, jwtOptionsProvider) {
$urlRouterProvider.otherwise('/app/home');
$stateProvider
.state("app", {
abstract: true,
url: "/app",
component: "appRouting"
})
.state("app.home", {
url: "/home",
component: "homeRouting"
})
.state("app.search", {
url: "/search/:q",
component: "searchRouting"
});
jwtOptionsProvider.config({
tokenGetter: ['authService', function (authService) {
return authService.getToken();
}],
whiteListedDomains: ['localhost']
});
$httpProvider.interceptors.push('jwtInterceptor');
});
If you are using angular-ui-router and have name of previous state then use :
$state.go('previousState', {}, { reload: true });
If you don't have the name of the previous state then you could use this piece of code it will run every time state change will occur.
$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from,fromParams) {
$rootScope.previousState = from.name;
$rootScope.currentState = to.name;
console.log('Previous state:'+$rootScope.previousState)
console.log('Current state:'+$rootScope.currentState)
});
you can refresh page by simply using native javascript. window.location.reload()
use $location.replace(). You can get the previous URL of where you came from using $document.referrer. $location.replace($document.referrer)

Refactor angular ui-router resolver to use it globally

I have resolve method inside angular config. It was written to protect the view from unauthorized access. Now the problem is, if I create a different route file, I have to copy the same resolve on each file. Is there any other way so that I can write it once and use it everywhere?
(function(){
'use strict';
var app = angular.module('app');
app.config(/* #ngInject */ function($stateProvider, $urlRouterProvider) {
var authenticated = ['$q', 'MeHelper', '$state', function ($q, MeHelper, $state) {
var deferred = $q.defer();
MeHelper.ready()
.then(function (me) {
if (me.isAuthenticated()) {
deferred.resolve();
} else {
deferred.reject();
$state.go('login');
}
});
return deferred.promise;
}];
$stateProvider
.state('index', {
url: "",
views: {
"FullContentView": { templateUrl: "start.html" }
}
})
.state('dashboard', {
url: "/dashboard",
views: {
"FullContentView": { templateUrl: "dashboard/dashboard.html" }
},
resolve: {
authenticated: authenticated
}
})
$urlRouterProvider.otherwise('/404');
});
})();
Edit: MeHelper is a Service.
To refactor your code, you should register a service and take the authentication code to the service.
Authenticate service:
app.factory('authenticateService', ['$q', 'MeHelper',
function($q,MeHelper){
var obj = {};
obj.check_authentication = function(params)
{
var deferred = $q.defer();
MeHelper.ready()
.then(function (me) {
if (me.isAuthenticated()) {
deferred.resolve();
} else {
deferred.reject();
$state.go('login');
}
});
return deferred.promise;
}
return obj;
}
]);
Then, use this service in any route file in resolve, taking this service name in dependency injection or the function parameter,
Route configuration file:
(function(){
'use strict';
var app = angular.module('app');
app.config(/* #ngInject */ function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url: "",
views: {
"FullContentView": { templateUrl: "start.html" }
}
})
.state('dashboard', {
url: "/dashboard",
views: {
"FullContentView": { templateUrl: "dashboard/dashboard.html" }
},
resolve: {
authenticated:
function(authenticateService) {
return authenticateService.check_authentication();
}
}
})
$urlRouterProvider.otherwise('/404');
});
})();
watch the below lines, this is what we changes in the route configuration to resolve.
the service is injected in below lines:
resolve: {
authenticated:
function(authenticateService) {
return authenticateService.check_authentication();
}
}
Do your check on route change.
app.run(function ($rootScope, $state) {
$rootScope.$on('$locationChangeSuccess', function () {
if (unauthorized && $state.current.name !== 'login') {
$state.go('login');
}
});
});

How can i pass parameter to injected functions in angular ui-router

So I have this routing piece of code:-
$stateProvider.state('app.dashboard', {
url: "/dashboard",
templateUrl: "app/components/dashboard/dashboard.html"
, resolve: {
factory: ["$ocLazyLoad", "$q", ['jquery-sparkline', 'dashboardCtrl'], loadSequence]
},
title: 'Dashboard',
ncyBreadcrumb: {
label: 'Dashboard'
}
And i have this function:-
function loadSequence($ocLL, $q, files) {
}
so basically what i want to do is passing ['jquery-sparkline', 'dashboardCtrl'] to the function loadSequence, these values are simple string values. Is there a way to this.
Maybe i don't understand you
(function () {
'use strict';
angular
.module('plunker')
.config(config);
config.$inject = ['$stateProvider'];
/* #ngInject */
function config($stateProvider) {
$stateProvider
.state('app.dashboard', {
url: '/dashboard',
templateUrl: 'app/components/dashboard/dashboard.html',
controller: 'dashboardCtrl',
controllerAs: 'dashboard',
resolve: {
dashboardService: dashboardService
},
title: 'Dashboard',
ncyBreadcrumb: {
label: 'Dashboard'
}
});
}
dashboardService.$inject = ['$ocLazyLoad', '$q'];
function dashboardService($ocLazyLoad, $q) {
return buttonService.getButtons().then(function (data) {
return data;
});
}
})();
(function () {
'use strict';
angular
.module('app.dashboard')
.controller('dashboardCtrl', dashboardCtrl);
dashboardCtrl.$inject = ['dashboardService','jquery-sparkline'];
function dashboardCtrl(dashboardService,jquery-sparkline) {
var vm = this;
vm.loadSequence = loadSequence;
function loadSequence($ocLL, $q, files) {
}
}
})();

AngularJS UI router: Block view

Right now i am making an AngularJS+UI router install application. But i have a problem, the problem is, that i want to disable access to the views, associated with the install application. I want to do it in resolve in the state config.
But the problem is i need to get the data from a RESTful API, whether the application is installed or not. I tried making the function, but it loaded the state before the $http.get request was finished.
Here was my code for the resolve function:
(function() {
var app = angular.module('states', []);
app.run(['$rootScope', '$http', function($rootScope, $http) {
$rootScope.$on('$stateChangeStart', function() {
$http.get('/api/v1/getSetupStatus').success(function(res) {
$rootScope.setupdb = res.db_setup;
$rootScope.setupuser = res.user_setup;
});
});
}]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404");
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
data: function($q, $state, $timeout, $rootScope) {
var setupStatus = $rootScope.setupdb;
var deferred = $q.defer();
$timeout(function() {
if (setupStatus === true) {
$state.go('setup-done');
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
})
.state('user-registration', {
url: "/install/user-registration",
templateUrl: "admin/js/partials/user-registration.html",
controller: "RegisterController"
})
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html"
})
.state('404', {
url: "/404",
templateUrl: "admin/js/partials/404.html"
});
}]);
})();
EDIT:
Here is what my ajax call returns:
Try this way:
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
setupStatus: function($q, $state, $http) {
return $http.get('/api/v1/getSetupStatus').then(function(res) {
if (res.db_setup === true) {
$state.go('setup-done');
return $q.reject();
}
return res;
});
}
}
})
Then inject setupStatus in controller:
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html",
controller: ['$scope', 'setupStatus', function ($scope, setupStatus) {
$scope.setupdb = setupStatus.db_setup;
$scope.setupuser = setupStatus.user_setup;
}]
})

UI router Unknown provider for injecting service into child state resolve

Got Unknown provider when injecting service into the child state resolve function. But if defined a resolve in the parent state, it just works. Below there are some sample codes:
I defined a service module
angular.module('services', [])
.factory('myService', function() {
// my service here
})
and initialize the app
var app = angular.module('app', ['services', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider.state('wizard', {
url: '/wizard',
abstract: true
})
.state('wizard.step1', {
url: '/step1',
templateUrl: ... ,
resolve: {
name: function(myService) {
// do something with mySerice
}
},
controller: function(name) {
// controller codes here
}
})
}]);
I got the error Unknown provider complaining about myService in the wizard.step1 resolve. But if I add a random resolve in the parent state, like
$stateProvider.state('wizard', {
url: '/wizard',
abstract: true,
resolve: {
a: function() { return 1; }
}
})
then it works without error. Wonder what happens here?
In your controller you have to inject your service MyService, so define something like this
.state('wizard.step1', {
url: '/step1',
templateUrl: ... ,
resolve: {
name: ['myService', function(myService) {
// do something with mySerice
}]
},
controller: ['name', function(name) {
// controller codes here
}]
})
You have to inject your service in your config function :
var app = angular.module('app', ['services', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', 'myService',
function($stateProvider, $urlRouterProvider, myService) {
...
Another way is to embed your resolve code in a service and assign directly the service :
app.config(['$stateProvider', '$urlRouterProvider' ,'mySuperService',function($stateProvider,
$urlRouterProvider, mySuperService) {
...
resolve: {
name: mySuperService()
}
.constant('mySuperService', function() {
var serv= function(){
// your code
}
return serv;
}

Resources