injecting service into angularjs app config - angularjs

I am trying to inject $http serivce into app config, but getting "unknown provider $http error".
woi.config(['$routeProvider', '$locationProvider','$http', function($routeProvider, $locationProvider,$http){
$routeProvider
.when("/channels", {
templateUrl: test,
resolve: {
app: function($http){
}
}
})
]});
My question is , is it possible to inject $http serivce in app config ,and if not then what are the other ways to do ajax call before controller and template is called.
Thanks,

You can directly pass $http or any dependency into the function, without defining it at config function. The DI framework of Angular would inject dependencies for resolve object functions.

Related

How do I call a service in angularJs config?

I have a service that needs to be called in the app's config module but it errors when I try to inject it. Any ideas? FYI - this service works perfectly fine in controllers when injected and executed.
app.config(['$routeProvider', 'myService', function($routeProvider, myService) {
var controller = myService.getSomeValue() ? 'FirstController', 'SecondController';
$routeProvider
.when('/', {
'templateUrl': '/myTemplate.html'
'controller': controller
})
});
Failed to instantiate module app due to:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=myService
The AngularJS framework operates in two phases, the config phase and the run phase. Only provider objects can be injected in the config phase. Services can only be injected during the run phase.
From the Docs:
module.config(configFn);
Use this method to configure services by injecting their providers, e.g. for adding routes to the $routeProvider.
Note that you can only inject providers and constants into this function.
For more about how to configure services, see Provider Recipe.
For more information, see
AngularJS module type API Reference - config
AngularJS Developer Guide - Providers - Summary

how to inject $http service on state change event in angular js?

I am using Ui-Route in angular js, and I want to call $http service on every state change. When I inject $http service in statechange event it gives an error of circular dependency or even I inject in interceptor the same error is showing. Please help me with this.
Thank you
You can put the service call in resolve for state
$stateProvider
.state('business-page', {
url: '/your-listing/:id',
controller: 'BusinessCtrl as vm',
templateUrl: 'pages/business/business.html',
title: 'Details',
resolve: {
listing: ['appDataFactory', '$stateParams', function (appDataFactory, $stateParams) {
return appDataFactory.getListingData($stateParams.id);
}]
}
})
where appDataFactory will be the service for $http request and the response can be solved as injection on the state controller

Consuming RESTful response via Angular service

I'm following scotch.io's tutorial on building a RESTful API while trying to get familiar with the MEAN stack.
I've followed pretty much everything so far, and got my RESTful API sending out JSON as intended. Should I try to access it via browser address bar or try it out with Postman it works.
I'm having problems with the consumption of said JSON response.
According to the tutorial, the Angular app is divided in controllers and services. The service uses $http to call the RESTful endpoint. My doubt is where and how should I use that service to call for the data.
Is it in the controller? Is the service exposed in a way that I can add its response to $scope?
I'm new to Angular/client-side routing, so please be gentle:) My code is below.
(Blog) Controller:
angular.module('BlogCtrl', []).controller('BlogController', function($scope, $http) {
$scope.tagline = 'Blog page!';
// can and should I call the service here?
});
Service:
angular.module('BlogService', []).factory('Post', ['$http', function($http) {
return {
// call to get all posts
get : function() {
return $http.get('/api/blog');
}
}]);
Routes:
angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
// blog page that will use the BlogController
.when('/blog', {
templateUrl: 'views/blog.html',
controller: 'BlogController'
})
$locationProvider.html5Mode(true);
}]);
Angular App:
angular.module('myApp', ['ngRoute', 'appRoutes', 'MainCtrl', 'BlogCtrl', 'BlogService']);
Yes, you can make $http call in your BlogController.
However if you want to use your 'Post' factory, you should inject it to controller
angular.module('BlogCtrl', []).controller('BlogController', function($scope, Post) {...}
and make the request
Post.get().then(
function(response){console.log(response.data)},
function(errorResponse){/*...*/}
);
(I think you should also read about $resource (https://docs.angularjs.org/api/ngResource/service/$resource). Maybe it is something what you could use to replace your Post factory ;))
You want to inject the service into controller ( or anywhere else you would use it) and then make the function call using the injected service object
angular.module('BlogCtrl', [])
.controller('BlogController', function($scope, Post) {
$scope.tagline = 'Blog page!';
// Use service to get data
Post.get().then(responsePromise){
$scope.someVariable = responsePromise.data;
}).catch(function(err){
console.warn('Ooops error!')
});
});

Restangular: Error: Unknown provider

I want to inject Restangular in my app to communicate with via REST.
So, here I am know with an error:
Error: [$injector:unpr] Unknown provider: RestangularProvider <- Restangular <- Api
Api is my own module here. What I'm doing:
Creating a main module called Dashboard
Creating a submodule called API
Now I want to use Restangular, but couldn't figure out how Angular is managing the dependencies...
Here is my sub-module where I inject Restangular:
angular.module( 'dashboard.api', ['restangular']).factory('Api', ['$http', 'Config', 'Restangular', function($http, Config, Restangular) {
My main module, Dashboard, doesn't need to inject Restangular, right?
angular.module( 'dashboard', [ 'dashboard.api'])
How is the injection-depency working within submodules? How can I
integrate Restangular in my app?
EDIT: Source file is included:
Okay I found the problem and the solution.
You have to differ between restangular(the module) and Restangular the service.
First, you have to include the main module of restangular into your app:
For me, it was this (polygon is a submodule of my app:
angular.module('polygons', ['restangular']);
Then, I wanted to inject restangular into a factory of that submodule:
angular.module('polygons').factory('polygonService', ['Restangular', polygonService]);
function polygonService(Restangular) {
// ...
});
This works for me. Hope this helps.

$httpProvider interceptor not working when $http is injected into a factory

I have a service called 'api', registered something like this:
angular
.module('myApp')
.factory('api', ['$http', function ($http) {
// do stuff with $http.get() etc here.
}]);
... and $http is being customized like this elsewhere:
angular
.module('myApp')
.factory('httpInterceptor', ['$rootScope', function ($rootScope) {
// do stuff to intercept http requests and auth things here
}]);
angular
.module('myApp')
.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
});
The interceptors are working when I directly inject $http into a controller, but when I use the api service in my controller, the $http customizations are not working. Looks like Angular does not add the intercepts by the point it's required by the factory I created.
How do I solve this?
The question was based on a wrong premise. The interceptors are in fact working, I was just using the wrong hook point. Instead of customizing the responseError property of the interceptor object, I was trying to intercept errors from the response property itself. This is why I thought the interceptors weren't working at all.
This problem does not really exist. The provider's interceptors are working correctly even in a factory.
You can try to make the httpInterceptor a variable inside the config instead of making it a factory:
angular
.module('myApp')
.config(function ($httpProvider) {
var httpInterceptor = ['$rootScope',
function($rootScope) {
// do stuff to intercept http requests and auth things here
}
];
$httpProvider.responseInterceptors.push(httpInterceptor);
});
Please note that I've also changed $httpProvider.interceptors to $httpProvider.responseInterceptors and the parameter passed to push() is not a string.
Let me know if that helps.
EDIT:
You can also consider using this plugin: https://github.com/witoldsz/angular-http-auth. It has this cool feature after the interception: "The authService will then retry all the requests previously failed due to HTTP 401 response."

Resources