Reputation: 14860
I'm issues trying to solve this problem I'm getting while trying to resolve data that needs to be injected to a controller's constructor. The controller is defined as follows...
var dashboardCtrl = function ($scope, profile) {
$scope.profile = profile;
$scope.fullName = function () {
if ($scope.profile == null)
return null;
return $scope.profile.firstName + " " + $scope.profile.lastName;
}
}
Notice it expects an object (profile
). This is how the controller is registered...
var centralApp = angular.module("centralApp", ['ngRoute', 'ngCookies']);
centralApp.factory("accountsFactory", accountsFactory);
centralApp .controller("dashboardCtrl", ["$scope", "profile", dashboardCtrl]);
The accounts factory simply performs account-related operations on a back-end RESTful service. Then, in the apps' config function I have defined the route as below...
var configFunc = function ($routeProvider, $httpProvider) {
$routeProvider.
when('/', {
templateUrl: '/dashboard',
controller: "dashboardCtrl",
resolve: {
profile: function (accountsFactory) {
return accountsFactory.profile();
}
}
});
}
and finally the accountsFactory
is defined as below...
var accountsFactory = function ($http, $q) {
return {
profile: function () {
var deferred = $q.defer();
$http.get("https://api.domain.com/profiles/me")
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(data);
});
return deferred.promise;
}
};
}
accountsFactory.$inject = ["$http", "$q"];
Now, what happens is that when the controller is instantiated I get the following error...
https://docs.angularjs.org/error/$injector/unpr?p0=profileProvider Unknown provider: profileProvider
The funny thing is that I can see that profile
contains the data I'm expecting when I use Chrome's Developer Tools, but Angular still insists that something went wrong
Where does this profileProvider
come from?
Why can I see on Chrome's Developer Tools that profile
is indeed instantiated with data?
I have already tried different approaches found on SO but I can't get passed this point. Any pointers will be highly appreciated
Upvotes: 1
Views: 51
Reputation: 21521
You don't need to inject profile
at the point where you create the controller. The router takes care of injecting profile
from your resolve function.
You don't have a profileProvider
which is why you get the error. You have a profile
resolver from the router. While both are injected they are different, the function in your resolve
is local to that particular state.
You should annotate profile
on the dependancy injection property $inject
of your controller instead:
var dashboardCtrl = function ($scope, profile) {
...
}
dashboardCtrl.$inject = ['$scope', 'profile'];
centralApp .controller("dashboardCtrl", ["$scope", dashboardCtrl]);
Upvotes: 1