How to pass initialization data to angular module? - angularjs

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);
};

Related

AngularJS - problems when using resolve

I basically need to call a server that's will return me a JSON structure before load the controller.
I was using many methods to archive that, but it's not working. It's don't show me any error and the page got blank. Any clue about what's going on ?
This is my controller..
angular
.module('app',[
'ngAnimate',
'ui.router',
'ui.bootstrap',
'ngCookies'
])
.run(function($rootScope) {
$rootScope.backendServer = "http://localhost:5000/";
})
.config(['$urlRouterProvider','$stateProvider', function($urlRouterProvider,$stateProvider) {
$stateProvider
.state('cms',{
url: '/my',
templateUrl: './app/templates/my.html',
controller : 'my',
resolve: {
dbState: function ($q) {
var defer = $q.defer();
Database.check().then(function (s) {
defer.resolve(s);
});
return defer.promise;
}
}
})
}])
.controller(function ($scope){
})
...and this is my service:
angular
.module('app')
.factory('Database',['$http', '$rootScope','$q', function($http, $rootScope, $q) {
return {
check: function () {
var call = $rootScope.backendServer + 'cms/database/check';
return $http.get(call);
}
}
}]);
don't create a defer object when you already returning a promise. so remove the defer and just return the factory function
also, inject the Database service to resolve
resolve: {
dbState: function(Database) {
return Database.check()
}
}
In the controller catch it like this
.controller("ctrl", function($scope, dbState) {
console.log(dbState.data)
})
Demo

Angular ui-route resolve injection issue

I am new in Angular JS and I stack with problem with inject resolve promise to controller.
I have next code:
var app = angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'ui.bootstrap'])
.config(function ($stateProvider, $urlMatcherFactoryProvider, $urlRouterProvider) {
$urlMatcherFactoryProvider.caseInsensitive(true);
$urlRouterProvider.otherwise('/refuel');
$stateProvider.state('refuels', {
url: '/refuel',
controller: 'refuelController',
controllerAs: 'refuelCtrl',
resolve: {
$refuelsPumpsResolve: function ($http) {
return $http({
url: "http://localhost:60000/Refuels/GetUserPumps",
method: "GET"
})
}
}
})
})
.controller('refuelController', function ($refuelsPumpsResolve) {
var $this = this;
this.isOpen = true;
this.isOpen = function () {
$this.isOpen = !$this.isOpen
}
this.pumpsData = $refuelsPumpsResolve;
});
However angular throws 'Unknown provider' exception for $refuelsPumpsResolve in controller.
I do not see any problem, more over the code was taken from ui-route tutorial on github.
Thanks for help
Try this, declaring the injection as you would normally do for say, a controller:
resolve: {
$refuelsPumpsResolve: ['$http', function ($http) {
return $http({
url: "http://localhost:60000/Refuels/GetUserPumps",
method: "GET"
})
}]
}

Angularjs custom headers with interceptors

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)

How to inject an external factory provider in angular config?

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!!!');
}
})();

callback for beginning of controller work

I have two controllers
angular.module('myApp.controllers', [])
.controller('Controller1',function(){
getController1();
})
.controller('Controller2',function(){
getController2();
})
I have some $http function in service with GET:
.service("geInfo", function() {
})
I want that my controllers will start only when i get the data of the service.
Do i have to use $q (promise), $watch or something else?
Does somebody can provide example?
Thanks!
You must resolve it in configuration phase:
(function() {
'use strict';
angular
.module('dashboardApp', [
'ngRoute'
])
.config(config);
/* #ngInject */
function config($routeProvider) {
$routeProvider
.when("/youUrl", {
templateUrl: "youtTemplate.html",
controller: "yourController",
resolve: {
initInfo: function(infoService){
return infoService.getInfo();
}
}
});
}
})();
Now you have initInfo in your controller:
.controller('Controller2',function($scope, initInfo){
$scope.info = initInfo;
})
By this way the router wont load the view until your service return initInfo.

Resources