I want to use ngdialog to do with the 401 status, but I get the error:Uncaught Error: [$injector:cdep]
angular.module('ws.site.master', [
'ngResource',
'ngCookies',
'ngSanitize',
'ngAnimate',
'ui.router',
'ngDialog'
]);
here I add a factory to do with the 401 status.
angular.module('ws.site.master').factory('authHttpResponseInterceptor',['$q','$location','ngDialog',function($q,$location,ngDialog){
return {
response: function(response){
if (response.status === 401) {
console.log("Response 401");
}
return response || $q.when(response);
},
responseError: function(rejection) {
if (rejection.status === 401) {
console.log("Response Error 401",rejection);
ngDialog.open({
template: '/common/templates/at.modal.security.html',
className: 'ngdialog-theme-default modal-security',
closeByDocument: false,
closeByEscape: false,
trapFocus: false,
controller: ['$scope', function($scope) {
$scope.defaultView = defaultView || 'login';
}]
});
$rootScope.isSecurityModal = true;
}
return $q.reject(rejection);
}
}
}]);
here add the authHttpResponseInterceptor to $httpProvider
angular.module('ws.site.master').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', 'ROUTE',
function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, ROUTE) {
$locationProvider.html5Mode(true);
angular.forEach(ROUTE, function(_route, _name){
$stateProvider.state(_name, _route);
});
$urlRouterProvider.otherwise('/');
$httpProvider.interceptors.push('authHttpResponseInterceptor');
}
]);
Error: $injector:cdep - Circular Dependency
Please check the angular docs about this
angular.module('myApp', [])
.factory('myService', function (myService) {
// ...
})
.controller('MyCtrl', function ($scope, myService) {
// ...
});
you are injecting 'ngDialog' twice, to you main module and then to factory and all of this is in the same 'ws.site.master'
For dialog window, you have to have bootstrap-tpls included in your html header. And the app should be as follows:
angular.module('myModule', [ 'ui.bootstrap']);
In controller or factory have:
app.controller('myController', function($scope, $modal) {
...
$scope.openPopup = function() {
$scope.modalInstance = $modal
.open({
animation : true,
backdrop : 'static',
templateUrl : 'yourTemplatePath/template.html',
controller : 'yourPopupController'
});
$scope.modalInstance.result.then(function(returnResult) {
$scope.returnResult = returnResult;
});
};
Related
I have this code:
app.js
var promptoWeb = angular.module('promptoWeb', ['ngMaterial', 'ngAnimate', 'ngMessages',
'ngAria', 'ui.router', 'ui.sortable', 'ngFileUpload']);
(function (app) {
app.factory('env', function () {
var domain = {domain: "http://localhost:8860/Elton"};
return domain;
});
app.config(['$stateProvider', '$urlRouterProvider', '$compileProvider',
function ($stateProvider, $urlRouterProvider, $compileProvider) {
self = this;
$compileProvider.preAssignBindingsEnabled(true);
$urlRouterProvider.otherwise('/');
$stateProvider.state('home', {
url: '/',
template: '<home-component></home-component>',
component: 'homeComponent',
params: {
selectedFilter: undefined
},
resolve: {
ldapGroup: function (authorizationService) {
return authorizationService.getLdapGroup() === 'WazeAdOps';
}
}
})
}]);
})(promptoWeb);
and home-component.js
(function (app) {
app.component('homeComponent', {
templateUrl: 'partials/home-partial.html',
controller: ['$scope', '$state', function ($scope, $state, ldapGroup) {
var self = this;
self.isFullList = false;
self.ldapGroup = ldapGroup;
self.addVoice = function () {
$state.go("add");
};
$scope.$broadcast('searchNoFilter');
}]
});
})
(promptoWeb);
why do i get an error in home-component that `ldapGroup is undefined?
and if I change to:
(function (app) {
app.component('homeComponent', {
templateUrl: 'partials/home-partial.html',
controller: ['$scope', '$state', 'ldapGroup',function ($scope, $state, ldapGroup) {
I get an error:
Error: [$injector:unpr] Unknown provider: ldapGroupProvider <- ldapGroup
I have also tried:
(function (app) {
app.component('homeComponent', {
templateUrl: 'partials/home-partial.html',
bindings: {
ldapGroup: '<'
},
controller: ['$scope', '$state', function ($scope, $state) {
var self = this;
self.isFullList = false;
$scope.isAdOps = !self.ldapGroup? true : self.ldapGroup;
I get self.ldapGroup === undefined
why do i get an error in home-component that ldapGroup is undefined?
Because you've told Angular to inject $scope and $state, so the third argument of the function is undefined.
controller: ['$scope', '$state', function ($scope, $state, ldapGroup)
I get an error:
Error: [$injector:unpr] Unknown provider: ldapGroupProvider <- ldapGroup
Because there is no service named ldapGroup. ldapGroup is a resolve of your state, which can be injected into the controller of that state. But your state has no controller. It has a component.
How to use components, and how resolves are bound to inputs of the component, is described in the documentation
I have a problem adding factory functions to my AngularJs module.
When I add the 'authInterceptor' factory function to my home view module. The view isn't loading. But when I delete the factory function it does load.
What am I doing wrong?
Home controller
'use strict';
angular.module('myApp.home', ['ngRoute'])
.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
// handle the case where the user is not authenticated
}
return $q.reject(rejection);
}
};
})
.config(['$routeProvider', function($routeProvider, $httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
$routeProvider.when('/', {
templateUrl: 'home/home.html',
controller: 'HomeCtrl'
});
}])
.controller('HomeCtrl', function($scope, $http, $window) {
console.log("Home Controller");
});
general module loader
// public/js/app.js
angular.module('myApp', [
'ngRoute',
'myApp.home'
])
.config(['$locationProvider', '$routeProvider',
function($locationProvider, $routeProvider, $httpProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/home'});
}])
.run(function($rootScope, $http){
$rootScope.my_message = 'test';
});
The problem is that your factory has a semi-colon, which breaks the following code.
.factory('authInterceptor', function () {
return 'a12345654321x';
}); //<==== remove this semicolon
//otherwise this breaks
.config(['$routeProvider', function($routeProvider, $httpProvider) {
//etc
}])
Edit for your second problem: You are missing the $httpProvider in your dependencies.
.config(['$routeProvider', function($routeProvider, $httpProvider
=>
.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider
I am trying to make user login and go on from / route in my angularfire app. But, somehow I got Unknown Provider Error while I am in MainController.
Here is my work;
var app = angular.module("myApp", ['firebase', 'ngRoute']);
This the factory of firebaseAuth.
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
return $firebaseAuth();
}
]);
This is from authenticating with routers angularfire tutorial.
app.run(["$rootScope", "$location", function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
if (error === "AUTH_REQUIRED") {
$location.path("/login");
}
});
}]);
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/login", {
controller: "LoginController",
templateUrl: "views/login.html",
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$waitForSignIn();
}]
}
}).when("/", {
controller: "MainController",
templateUrl: "views/home.html",
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireSignIn();
}]
}
});
}]);
In the login page I can sign in via google pop up and I can see the cookie in the browser.
app.controller("LoginController", ["$scope", "currentAuth", "Auth", function($scope, currentAuth, Auth) {
$scope.auth = Auth;
$scope.auth.$onAuthStateChanged(function(firebaseUser) {
$scope.firebaseUser = firebaseUser;
});
}]);
When I open "/" path, it fails and creating error like this
app.controller("MainController", [ "$scope", "$location", "$firebaseArray", "currentAuth", function($scope, $location, $firebaseArray, currentAuth) {
var ref = firebase.database().ref();
if (currentAuth == undefined || currentAuth == null) {
$location.path('/login');
}
}]);
Is there something wrong that I miss ?
Thank you.
I am trying to migrate my angularjs 1.2 app (which is working fine now) to angularjs 1.3. But I am getting the below error.
[$injector:modulerr] Failed to instantiate module constructionApp due
to: TypeError: Unable to get property 'push' of undefined or null
reference at Anonymous function (http://localhost/app/app.js:33:5)
Also, this is the code I am having in my app.js
var cmApp = angular.module('myApp',
['xeditable', 'ui.bindonce', 'gantt', 'angularFileUpload', 'ui.bootstrap', 'ui.router', 'ngAnimate', 'wc.Directives']);
cmApp.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', '$location', function (scope, $q, $location) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401 || status == 404) {
$location.path('#/Error');
return;
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor); ***get error at this line
// For any unmatched url, redirect to /home
$urlRouterProvider.otherwise("/Home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "/app/views/home.html",
controller: "homeController"
})
.state('somepage', {
url: "/somepage/:ID",
templateUrl: "/app/views/somepage.html",
controller: "somePageController"
})
});
Please help me to solve this migration issue.
I am using angular-ui-router's resolve to get data from server before moving to a state. Sometimes the request to the server fails and I need to inform the user about the failure. If I call the server from the controller, I can put then and call my notification service in it in case the call fails. I put the call to the server in resolve because I want descendant states to wait for the result from the server before they start.
Where can I catch the error in case the call to the server fails? (I have read the documentation but still unsure how. Also, I'm looking for a reason to try out this new snippet tool :).
"use strict";
angular.module('MyApp', ["ui.router"]).config([
"$stateProvider",
"$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/item");
$stateProvider
.state("list", {
url: "/item",
template: '<div>{{listvm}}</div>' +
'<a ui-sref="list.detail({id:8})">go to child state and trigger resolve</a>' +
'<ui-view />',
controller: ["$scope", "$state", function($scope, $state){
$scope.listvm = { state: $state.current.name };
}]
})
.state("list.detail", {
url: "/{id}",
template: '<div>{{detailvm}}</div>',
resolve: {
data: ["$q", "$timeout", function ($q, $timeout) {
var deferred = $q.defer();
$timeout(function () {
//deferred.resolve("successful");
deferred.reject("fail"); // resolve fails here
}, 2000);
return deferred.promise;
}]
},
controller: ["$scope", "data", "$state", function ($scope, data, $state) {
$scope.detailvm = {
state: $state.current.name,
data: data
};
}]
});
}
]);
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<div ng-app="MyApp">
<ui-view />
</div>
Old question but I had the same problem and stumbled on this in ui-router's FAQ section
If you are having issues where a trivial error wasn't being caught
because it was happening within the resolve function of a state, this
is actually the intended behavior of promises per the spec.
errors within resolve.
So you can catch all resolve errors in the run phase of your app like this
$rootScope.$on('$stateChangeError',
function(event, toState, toParams, fromState, fromParams, error){
// this is required if you want to prevent the $UrlRouter reverting the URL to the previous valid location
event.preventDefault();
...
})
The issue is that if any of the dependencies in the route resolve is rejected, the controller will not be instantiated. So you could convert the failure to data that you can detect in the instantiated controller.
Example Pseudocode:-
data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {
return $timeout(function () { //timeout already returns a promise
//return "Yes";
//return success of failure
return success ? {status:true, data:data} : {status:false}; //return a status from here
}, 2000);
}]
and in your controller:-
controller: ["$scope", "data", "$state", function ($scope, data, $state) {
//If it has failed
if(!data.status){
$scope.error = "Some error";
return;
}
$scope.detailvm = {
state: $state.current.name,
data: data
};
If you are making an $http call or similar you can make use of http promise to resolve the data always even in case of failure and return a status to the controller.
Example:-
resolve: {
data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {
return $http.get("someurl")
.then(function(){ return {status:true , data: "Yes"} },
function(){ return {status:false} }); //In case of failure catch it and return a valid data inorder for the controller to get instantated
}]
},
"use strict";
angular.module('MyApp', ["ui.router"]).config([
"$stateProvider",
"$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/item");
$stateProvider
.state("list", {
url: "/item",
template: '<div>{{error}}</div><div>{{listvm}}</div>' +
'<a ui-sref="list.detail({id:8})">go to child state and trigger resolve</a>' +
'<ui-view />',
controller: ["$scope", "$state", function($scope, $state){
$scope.listvm = { state: $state.current.name };
}]
})
.state("list.detail", {
url: "/{id}",
template: '<div>{{detailvm}}</div>',
resolve: {
data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {
return $http.get("/").then(function(){ return {status:true , data: "Yes"} }, function(){ return {status:false} })
}]
},
controller: ["$scope", "data", "$state", function ($scope, data, $state) {
$scope.detailvm = {
state: $state.current.name,
data: data.status ? data :"OOPS Error"
};
}]
});
}
]);
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script data-require="angular-ui-router#*" data-semver="0.2.10" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<div ng-app="MyApp">
<ui-view></ui-view>
</div>