I am trying to add a custom header using interceptors to every request I make on the app and I get the following error
Uncaught Error: [$injector:unpr] Unknown provider:
httpRequestInterceptorProvider <- httpRequestInterceptor <- $http <-
$templateFactory <- $view <- $state
// Ionic Starter App
(function () {
'use strict';
var app = angular
.module('app', ['ionic', 'auth0.lock', 'angular-jwt'])
.config(config)
.factory(factory)
factory.$inject = ['httpRequestInterceptor'];
config.$inject = ['$stateProvider', '$urlRouterProvider', 'lockProvider', 'jwtOptionsProvider', '$httpProvider'];
function factory(httpRequestInterceptor) {
return {
request: function (config) {
config.headers['X-switch-using'] = isApple;
return config;
}
}
}
function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider, $httpProvider) {
$stateProvider
// setup an abstract state for the tabs directive
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'components/menu/menu.html',
})
.state('app.home', {
url: '/home',
views: {
'menuContent': {
templateUrl: 'components/home/home.html'
}
}
})
.state('app.dashboard', {
url: '/dashboard',
views: {
'menuContent': {
templateUrl: 'components/template/template.html'
}
}
})
.state('app.signin', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'components/login/login.html'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
$httpProvider.interceptors.push('httpRequestInterceptor');
lockProvider.init({
clientID: AUTH0_CLIENT_ID,
domain: AUTH0_DOMAIN,
options: {
auth: {
redirect: false,
params: {
scope: 'openid',
device: 'Mobile device'
}
}
}
});
// Configuration for angular-jwt
jwtOptionsProvider.config({
tokenGetter: function () {
return localStorage.getItem('id_token');
},
whiteListedDomains: ['localhost'],
unauthenticatedRedirectPath: '/login'
});
}
})();
When I try to $httpProvider.interceptors.push('httpRequestInterceptor');
Any ideas? Cheers!
The problem is you are inject interceptor here factory.$inject = ['httpRequestInterceptor']; but what exactly the httpRequestInterceptor is ? you have not create anything with that name.
What you need to do is change below functions name to httpRequestInterceptor from factory:
function factory(httpRequestInterceptor)
and make it function httpRequestInterceptor()
Then replace .factory(factory) with .factory(httpRequestInterceptor) and you can remove factory.$inject if you dont need to inject anything else.
Problem 1
The first problem is that there is no dependency in your app like httpRequestInterceptor.
Problem 2
The 2nd major problem is that you can not inject a simple factory or service in the config phase of Angular.
From the docs
Only providers and constants can be injected into configuration
blocks. This is to prevent accidental instantiation of services before
they have been fully configured.
So consider changing your code like this:
// Ionic Starter App
(function () {
'use strict';
var app = angular
.module('app', ['ionic', 'auth0.lock', 'angular-jwt'])
.config(config)
//.factory(factory) // Removed factory
config.$inject = ['$stateProvider', '$urlRouterProvider', 'lockProvider', 'jwtOptionsProvider', '$httpProvider'];
function factory() {
return {
request: function (config) {
config.headers['X-switch-using'] = isApple;
return config;
}
}
}
function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider, $httpProvider) {
/** your state configuration here **/
$httpProvider.interceptors.push(factory);
/** your lockprovider and jwtOptionsProvider here **/
}
})();
I don't see a factory with httpRequestInterceptor which you are injecting in your factory named factory. If at all the factory httpRequestInterceptor is another module, you have inject that module as a dependency in your app module.
var app = angular
.module('app', ['ionic', 'auth0.lock', 'angular-jwt','inject
the module which has the httpRequestInterceptor factory'])
.config(config)
.factory(factory)
Related
I am working with IONIC Framework (Angularjs)
I am receiving below error,
463788 error Error: [ng:areq] http://errors.angularjs.org/1.4.3/ng/areq?p0=PaymentCtrl&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at http://localhost:8100/lib/ionic/js/angular/angular.min.js:6:416
at Sb (http://localhost:8100/lib/ionic/js/angular/angular.min.js:22:18)
at Qa (http://localhost:8100/lib/ionic/js/angular/angular.min.js:22:105)
at http://localhost:8100/lib/ionic/js/angular/angular.min.js:79:497
at I.appendViewElement (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:4463)
at Object.O.render (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:16:17590)
at Object.O.init (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:16:16825)
at I.render (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:3419)
at I.register (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:3150)
Here is my code for controller.
define(['ionic', 'ionicAngular', 'angular',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular) {
'use strict';
console.log('Payment controller ');
var PaymentCtrl = function ($scope, PaymentSvc,$state, $ionicLoading) {
/*$scope.phoneNumberVerification = function() { $state,$ionicPopup,
console.log('PhoneNumber controller added1 ');
$ionicLoading.hide();
$state.go('tab.eateries');
};*/
// When button is clicked, the popup will be shown...
};
return PaymentCtrl;
});
Serveics.js
define(['ionic', 'ionicAngular', 'angular',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular) {
'use strict';
//console.log('service modules');
var PaymentSvc = function(){
console.log('serverices call');//var svc = this;
}
return PaymentSvc;
});
// });*/
payment.js
define(['ionic', 'ionicAngular', 'angular',
'./modules/payment/controllers/paymentctrl',
'./modules/payment/services/services',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular,
paymentCtrl,
paymentSvc) {
'use strict';
console.log('payment.js modules');
var payment = angular.module('payment', ['ionic'])
.controller('PaymentCtrl', paymentCtrl)
.service('PaymentSvc',paymentSvc);
return payment;
});
No need to inject ['angular','ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter']. Ionic automatically inject angular decencies when you inject ['ionic']
Just write your controller directly
angular.module('starter', ['ionic']).controller('PayCtrl',function ($scope,$state,$ionicLoading,PaymentSvc){
//starter is the app name come from ng-app="starter"
$ionicLoading.show();
$scope.phoneNumberVerification = function(){
console.log('PhoneNumber controller added1');
$ionicLoading.hide();
$state.go('tab.eateries');
};
});
I advise you to organize your javascript project files to in 3 files:
app.js which contains
angular.module('starter', ['ionic', 'starter.controllers','starter.services'])..config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
}).state('app.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/home.html',
controller : 'HomeCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/home');
});
controller.js which contains your controllers
angular.module('starter.controllers', []).controller('AppCtrl', function('PayCtrl',function ($scope,$state,$ionicLoading,PaymentSvc){
$ionicLoading.show();
$scope.phoneNumberVerification = function(){
console.log('PhoneNumber controller added1');
$ionicLoading.hide();
$state.go('tab.eateries');
};
});
service.js which contains you connections to server
angular.module('starter.services', []).factory('PaymentSvc',function($http,$q){
});
it is an injection error. for example, if you inject ['a','b','c'] you must have it in your function in the same order and amount: function(a,b,c). in your case, you have more parameters in the injection than the parameters in your controller function.
Please consider the this code where the routeProvider is needed to inject page(n).html in ng-view.
In addition to the console error:
unknown provider: $routeProviderProvider <- $routeProvider
The argument to function routeIt is the name of the page to navigate to, How can I mix a conditional switch with routeProvider.when in order to call the page matching the argument in the most efficient manner? Thanks
(function () {
'use strict';
angular
.module('appModule')
.controller('MainMenuCtrl', ['$scope', '$http', 'TogglerFactory', '$routeProvider', MainMenuCtrl]);
function MainMenuCtrl($scope, $http, Toggler, routeProvider) {
$http.get('models/mainMenu.json').then(
function (response) {
$scope.menuItems = response.data;
},
function (error) {
alert("http error");
}
)
function routeIt (page) {
routeProvider
.when('/page1', {
url: "/page1",
templateUrl: 'views/page1.html',
controller: 'Page1Ctrl'
})
.when('/page2', {
url: "/page2",
templateUrl: 'views/page2.html',
controller: 'Page2Ctrl'
})
}
$scope.itemClicked = function (item){
Toggler.menuToggle();
routeIt(item);
}
}
})();
Service providers aren't available for injection in run phase (i.e. anywhere but provider services and config blocks). It is possible to make route provider injectable and configure it after config phase,
app.config(function ($provide, $routeProvider) {
$provide.value('$routeProvider', $routeProvider);
});
And controllers aren't the best places to implement any logic (e.g. route hot-plug).
Ok you're using your routeProvider wrong you need to configure your routes inside .config blocks
angular.module('myApp', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/page1', {
url: "/page1",
templateUrl: 'views/page1.html',
controller: 'Page1Ctrl'
}
})
If you want to change the url from your controller use $location.path('/page1'); inside your controller.
I have a webmethod on my remote server returning a JSon object.
Said json object contains strings which are required for the module to proper work.
So, is there a way to pass something to an angular module?
An idea could be to perform an http request inside of the initialization of the module:
$scope.init = function(){
$http.get ()
...
then(){
$scope.mydata = result;
}
};
But that would be asynchronous...
If you are worried about the async nature of an HTTP request to fill out your $scope.mydata variable, then you need to include this in a RESOLVE in your route.
I'm using UI-ROUTER in my current project:
(function() {
'use strict';
angular
.module('capps.core')
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home.capps', {
url: '/',
template: '<ui-view/>',
data: {
requireLogin: true
},
resolve:{
resolveFunction: resolveFunction
}
});
}
]);
resolveFunction['$inject'] = ['$http'];
function resolveFunction($http) {
return $http.get(API_URL)
.then(function(res) {
console.log(res);
});
}
})();
Then in your controller, you can pass 'resolveFunction' as a dependency... then use that to assign to your $scope.myData.
...
angular.controller('myController', myController);
myController.$inject = ['resolveFunction', '$scope'];
function myController(resolveFunction, $scope) {
$scope.mydata = resolveFunction.data;
console.log(mydata);
};
I'm trying to inject a factory provider from another js file but it can't locate the provider. If this can't be done, what is the better way?
demo.config.js
function configState($stateProvider, $urlRouterProvider, $compileProvider, demoProvider) {
// Optimize load start with remove binding information inside the DOM element
$compileProvider.debugInfoEnabled(true);
// Set default state
$urlRouterProvider.otherwise("/dashboard");
$stateProvider
// Dashboard - Main page
.state('dashboard', {
url: "/dashboard",
templateUrl: "views/dashboard.html",
data: {
pageTitle: 'Dashboard',
}
})
}
angular
.module('demoApp')
.config(configState)
.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
demo.provider.js
(function () {
'use strict';
angular
.module('demoApp')
.provider('demo', function() {
return {
$get: function() {
return {
title: "Starcraft"
}
}
}
});
})();
I always put my own provider to controllers. Like in my directive
(function() {
'use strict';
angular.module('yourMod').directive('yourViewPage', yourViewPage);
angular.module('yourMod').controller('YourViewPageCtrl', YourViewPageCtrl);
function YourViewPageCtrl(YourProvider) {
//your code!!!
// Example YourProvider.getSomeThing();
console.log('My life for Aiur!!!');
}
})();
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;
}