I have three files app.js, common.services.js and tokenContainer.js . When i tried to inject tokenContainer dependency to interceptor of app.js, I get an error :
Uncaught Error: [$injector:unpr] Unknown provider: tokenContainerProvider <- tokenContainer <- $http <- $templateRequest <- $compile
common.service.js file
(function () {
"use strict";
angular
.module("common.services",
["ngResource"])
.constant("appSettings",
{
serverPath: "http://localhost:6359"
});
}());
tokenContainer.js file :
(function () {
"use strict";
angular
.module("common.services")
.factory("tokenContainer",
[tokenContainer])
function tokenContainer() {
var container = {
token: ""
};
var setToken = function (token) {
container.token = token;
};
var getToken = function () {
};
return {
getToken: getToken
};
};
})();
app.js file :
(function () {
var app = angular.module("productManagement",
["ngRoute", "common.services"]);
app.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when("/products", {
templateUrl: "app/products/productListView.html",
controller: "ProductListCtrl as vm"
})
.when("/products/create", {
templateUrl: "app/products/productCreateView.html",
controller: "ProductCreateCtrl as vm"
})
.when("/login", {
templateUrl: "app/login/login.html",
controller: "loginController as vm"
})
.otherwise({ redirectTo: "/products" });
$httpProvider.interceptors.push(function (appSettings, tokenContainer) {
return {
'request': function (config) {
// ToDo :
return config;
}
};
});
});
}());
Related
This is my Js code
(function () {
angular.module('app',[])
.factory('code', function ($http, svc, $q) {
function getCodeByID(id) {
return $http.get(svc.get('my-application') + id)
.then(function (res) {
return res;
});
}
})
})();
This is my Spec.js file
describe('MyController', function() {
var data, svc, code;
// Set up the module
//beforeEach(module('app'));
beforeEach(angular.mock.module('app'));
beforeEach(inject(function(_data_) {
data = _data_;
}));
beforeEach(inject(function(_svc_) {
svc = _svc_;
}));
beforeEach(inject(function(_code_) {
code = _code_;
}));
it('Should exist', function() {
expect(code).toBeDefined();
});});
Getting this error:
Error: [$injector:unpr] Unknown provider: dataProvider <- data
https://errors.angularjs.org/1.7.4/$injector/unpr?p0=dataProvider%20%3C-%20data
at node_modules/angular/angular.js:138:12
at node_modules/angular/angular.js:4905:19
at Object.getService [as get] (node_modules/angular/angular.js:5065:32)
at node_modules/angular/angular.js:4910:45
at getService (node_modules/angular/angular.js:5065:32)
at injectionArgs (node_modules/angular/angular.js:5090:58)
at Object.invoke (node_modules/angular/angular.js:5114:18)
at UserContext.WorkFn (node_modules/angular-mocks/angular-mocks.js:3439:20)
Error: Declaration Location
at window.inject.angular.mock.inject (node_modules/angular-mocks/angular-mocks.js:3402:25)
at Suite.<anonymous> (src/app/epcCodes/epc.spec.js:9:16)
at src/app/epcCodes/epc.spec.js:2:1
I don't know why I am getting this error, I have added all the dependency injection that's needed for my project.
Can you provide me the solution for this?
You only need one of those beforeEach blocks where you are injecting your services -- though this has nothing to do with your issue.
This one does have to do with your issue -- you are "telling" your test to inject a data component/service/factory when one apparently does not exist in your code. What are you expecting data to be?
angular.module('Svc', [])
.factory('Svc', function (Data, $injector, $http) {
var ConfigData = Data;
var Svc = {};
Svc.get = function (key) {
return ConfigData[key];
};
Svc.loadResourcePaths = function (resources) {
resources.forEach(function (resource) {
$http.get(Svc.get('security-api') + 'resources?name=' + resource)
.then(function (response) {
if (response.data.totalElements === 1) {
ConfigData[resource] = response.data.content[0].href;
} else {
}
})
})
};
return Svc;
});
(function () {
angular
.module('app', [
'ConfigSvc',
'AuthUtils',
'ngCsv'
])
.constant('APPNAME', 'ui')
.constant('APPLABEL', 'app_label')
.constant('APPPREFIX', 'App_name')
.config(function ($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('grey', {'default': '900'})
.accentPalette('blue', {'default': '400'})
;
})
.config(function routesConfig($stateProvider, $urlRouterProvider, $locationProvider, $mdAriaProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
template: '<app></app>',
data: {
label: 'Home',
icon: 'home',
menu: true
}
});
});
angular.element(document).ready(function () {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('appConfig.json')
.then(function (response) {
angular.module('app').constant('Data', response.data);
return $http.get('appFeatures.json')
})
.then(function (response) {
angular.module('app').constant('ccAppFeatures', response.data);
})
.finally(function () {
angular.bootstrap(document, ['app']);
});
});})();
I want to remove exclamation marks from url state routing like my url is now http://localhost:3000/#!/auth/register
i just want to remove this "!" marks from url after "#"
Is it possible to do? with mean.io
here is my app.js/system.js
'use strict';
//Setting up route
angular.module('mean').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// For unmatched routes:
//$urlRouterProvider.otherwise('/');
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
$location.url('/auth/login');
}
});
return deferred.promise;
};
// console.log($stateProvider);
// states for my app
$stateProvider
.state('tasks', {
url: '/kanban/:projectId/:projectSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve: {
loggedin: checkLoggedin,
onEnter: function($stateParams,$state, $uibModal) {
if ( $stateParams.projectId != "" ) {
updateTopMenu('Kanban','task','#!/kanban/'+$stateParams.projectId+'/'+$stateParams.projectSlug);
updateTopMenu('Schedule','schedule','#!/schedule');
}
}
}
}).state('home',{
url:'/',
templateUrl: 'projects/views/index.html',
controller: 'ProjectController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskEdit',{
url:'/kanban/:projectId/:projectSlug/:taskSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskAdd',{
url: "/task/taskAdd",
onEnter: function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: "system/views/include/model.html",
resolve: {},
controller: function($scope, $state, itemService) {
/*
$scope.state = $state.current;
$scope.params = $stateParams;
$scope.item = itemService.get($stateParams.id);
*/
$scope.ok = function () {
$scope.$close('clicked ok');
};
$scope.dismiss = function () {
$scope.$dismiss('clicked cancel');
};
}
}).result.then(function (result) {
// $scope.$close
alert('result ->' + result);
}, function (result) {
// $scope.$dismiss
return $state.transitionTo("home");
alert('dismiss ->' + result);
}).finally(function () {
// handle finally
return $state.transitionTo("tasks");
});
}
});
}
]).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
you have configured it here
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
remove this line to get ! removed from url
or enable html5mode using below code to remove # from url
$locationProvider.html5Mode(true);
but please read more about how url routes are handled in angular, and server side routing vs client side routing etc, before enabling html5mode
Change $locationProvider.hashPrefix('!'); to $locationProvider.hashPrefix('');
System.js
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
File structure:
app.js
(function () {
"use strict";
var app = angular.module("app", ["common.services", "ngRoute", "ngResource"])
app.config(function ($routeProvider) {
$routeProvider
// route for the home page
//.when('/', {
// controller: 'mainController',
// templateUrl: 'app/linkPages/home.html'
//})
// route for the about page
//.when('/about', {
// controller: 'aboutController',
// templateUrl: 'app/linkPages/about.html'
//})
// route for the contact page
//.when('/contact', {
// controller: 'contactController',
// templateUrl: 'app/linkPages/contact.html'
//})
.when('/', {
controller: 'AgencyListCtrl',
templateUrl: 'app/agencies/agencyListView.html'
})
//.when('/agencyEditView', {
// controller: 'AgencyEditCtrl',
// templateUrl: 'app/agencies/agencyEditView.html'
//});
});
// create the controller and inject Angular's $scope
app.controller('mainController', function ($scope) {
// create a message to display in our view
$scope.message = 'This is the Main controller page';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'This is the about controller page';
});
app.controller('contactController', function ($scope) {
$scope.message = 'This is the contact controller page';
});
}());
common.services.js
(function () {
"use strict";
angular
.module("common.services",
["ngResource"])//common.services
.constant("appSettings",
{
serverPath: "http://localhost:53403/" // will replace production server url
});
}());
agencyResource.js
(function () {
"use strict";
angular.module("app")//common.services
.factory("agencyResource"
["ngResource", "$resource",
"appSettings",
agencyResource])
function agencyResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/v1/agencies/:id", null,
{
'update': { method: 'PUT' },
});
}
}());
agencyListCtrl.js
(function () {
"use strict";
angular
.module("app")
.controller("AgencyListCtrl",
["agencyResource",
AgencyListCtrl]);
function AgencyListCtrl(agencyResource) {
var vm = this;
//agencyResource.query({ $filter: "contains(Abbr,'IOT')" },
// function (data) {
// vm.agencies = data;
// console.log(result);
//})
agencyResource.query({},
function (data) {
vm.agencies = data;
console.log(result);
})
}
}());
ERROR:
HTML1300: Navigation occurred. index.html Error: [$injector:unpr]
Unknown provider: agencyResourceProvider <- agencyResource <-
AgencyListCtrl
http://errors.angularjs.org/1.5.9/$injector/unpr?p0=agencyResourceProvider%20%3C-%20agencyResource%20%3C-%20AgencyListCtrl
at Anonymous function (http://localhost:61924/Scripts/angular.js:4554:13)
at getService (http://localhost:61924/Scripts/angular.js:4707:11)
at Anonymous function (http://localhost:61924/Scripts/angular.js:4559:13)
at getService (http://localhost:61924/Scripts/angular.js:4707:11)
at injectionArgs (http://localhost:61924/Scripts/angular.js:4731:9)
at instantiate (http://localhost:61924/Scripts/angular.js:4774:7)
at $controller (http://localhost:61924/Scripts/angular.js:10533:7)
at link (http://localhost:61924/Scripts/angular-route.js:1056:9)
at Anonymous function (http://localhost:61924/Scripts/angular.js:1258:11)
at invokeLinkFn (http://localhost:61924/Scripts/angular.js:10095:9)
I am not sure weather I have injected everything right here? Any help would be appreciated. This is my first angular app so I am a little green. Stack Overflow is telling me I have to type more details but the code post are pretty self explanatory. I
The answer is that I was declaring ngResource in the agencyResource.js file. It should look like this. MY BAD.
agencyResource.js
(function () {
"use strict";
angular.module("common.services")//common.services
.factory("agencyResource",
[
"$resource",
"appSettings",
agencyResource
])
function agencyResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/v1/agencies/:id", null,
{
'update': { method: 'PUT' },
});
}
}());
I have a error where Safari is trowing error that my controllers are not a function
Error: [ng:areq] Argument 'TranslateController' is not a function, got undefined
My router calling controller here ->
(function() {
'use strict';
angular
.module('welcome.module')
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('welcome', {
url: '/welcome',
views: {
'header': {
templateUrl: 'app/welcome/header.html',
controller: 'TranslateController'
},
'sidebar': {},
'content': {
templateUrl: 'app/welcome/welcome.html',
controller: 'WelcomeController'
},
'footer': {
templateUrl: 'app/welcome/footer.html',
controller: 'WelcomeFooterController'
}
}
})
}]);
})();
My controller ->
(function() {
'use strict';
angular
.module('welcome.module')
.controller('TranslateController', TranslateCtrl);
TranslateCtrl.$inject = ['$translate', '$scope'];
function TranslateCtrl($translate, $scope) {
'ngInject';
const self = this;
$scope.headerFix = true;
activate();
function activate() {
translate();
}
function translate() {
$scope.changeLanguage = function(langKey) {
$translate.use(langKey);
};
}
}
})();
I have definition of the module of course:
(function() {
'use strict';
angular
.module('welcome.module', [
'ui.router'
]);
})();
I defined controllers and modules and everything in my html.
Everything is working smooth on mozila and chrome but not on Safari :(
Do you have any idea how to solve this issue ?
angular.module('welcome.module')
.controller('TranslateController', ['$scope', '$translate',
function($scope, $translate) {
$scope.headerFix = true;
activate();
function activate() {
translate();
}
function translate() {
$scope.changeLanguage = function(langKey) {
$translate.use(langKey);
};
}
}
]);
Fixed it
I'm trying to update my nav bar every time the route changes, and I've tried this, however it doesn't seem to be working. It's supposed to write bob every time the view changes, but it only writes it when the controller loads.
nav.controller.js
angular.module('app')
.controller('navController', ['$scope', '$state', function ($scope, $state) {
var timeSpan;
$scope.user;
...
// Update when the view changes.
$scope.reload = function () {
$state.reload();
};
$scope.$state = $state;
$scope.$watch('$state.$current.locals.globals.view', function () {
console.log('bob');
$scope.user = userService.get();
});
...
$scope.reroute = function(route){
$state.go(route);
};
}]);
route.js
angular.module('SimPlannerApp')
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('/','/signin');
$stateProvider
.state('signin', {
url: "/signin",
templateUrl: 'views/signin.html',
controller: 'signinController'
})
.state('menu', {
url: "/menu",
templateUrl: 'views/menu.html',
controller: 'menuController',
resolve: {
config: function (configService) {
return configService.getConfig()
.then(function(response){
return response.data;
})
.catch(function(error){
console.log('Error : ', error);
return undefined;
});
}
}
})
.state('view', {
url: '/view/:view',
templateUrl: 'views/view.html',
controller: 'viewController',
resolve: {
view: function ($stateParams, configService) {
return configService.getConfig()
.then(function(response){
var config = response.data;
for (var i = 0; i < config.views.length; i++) {
if (config.views[i].route === $stateParams.view) {
return config.views[i];
}
}
return undefined;
})
.catch(function(error){
console.log('Error : ', error);
return undefined;
});
},
config: function (configService) {
return configService.getConfig()
.then(function(response){
return response.data;
})
.catch(function(error){
console.log('Error : ', error);
return undefined;
});
}
}
})
.state('404', {
url: '{path:.*}',
templateUrl: 'views/404.html',
controller: 'errorController'
});
});
PS:
Propably should mention I'm using AngularJS with ui-router.
Not sure if I fully understand but would it not be better to use $stateChangeSuccess to detect when the route changes? I use this in the .run block
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })
but you could place this in your Controller
https://github.com/angular-ui/ui-router/wiki
You can handle with $locationChangeStart like below:
$rootScope.$on('$locationChangeStart', function () {
console.log('bob');
});
You should write this in .module.run() function.
angular
.module()
.run(function($rootScope) {
// to Here
})