ui-router views cannot find method in controller - angularjs

I have this ui-router and it works fine it redirect me to bubblesettings page.
.state('bubblesettings', {
url: '/bubble/:bubbleId/settings',
data: {
authorizedRoles: [USER_ROLES.editor]
},
views: {
'navigation': {
templateUrl: "/js/shared/partials/navigation.html"
},
'main': {
templateUrl: "/js/shared/partials/bubbles/bubble-settings.html"
}
}
})
In that controller i want to do a call to a service to get bubble users.
(function () {
'use strict';
angular
.module('raqtApp')
.controller('BubblesSettingsController', BubblesSettingsController);
BubblesSettingsController.$inject = ['$scope', '$rootScope', '$stateParams', 'BubblesService', '$state'];
function BubblesSettingsController($scope, BubblesService, $rootScope, $stateParams, $state) {
$scope.bubbleId = $state.params.bubbleId;
$scope.getMembersInBubble = function (bubbleId) {
BubblesService.getBubbleUsers(bubbleId)
.then(function (data) {
$scope.bubbleUsers = data;
console.log('Sucesss');
},
function (data) {
console.log('Fail..');
})
};
}
})();
When i call my function getMembersInBubble i get
TypeError: BubblesService.getBubbleUsers is not a function
at Scope.BubblesSettingsController.$scope.getMembersInBubble (http://localhost:3604/js/bubbles/settings/bubble-settings-controller.js:20:28)
at fn (eval at <anonymous> (https://code.angularjs.org/1.4.0-rc.1/angular.js:12931:15), <anonymous>:2:350)
at ngEventDirectives.(anonymous function).compile.element.on.callback (https://code.angularjs.org/1.4.0-rc.1/angular.js:22919:17)
at Scope.$get.Scope.$eval (https://code.angularjs.org/1.4.0-rc.1/angular.js:15574:28)
at Scope.$get.Scope.$apply (https://code.angularjs.org/1.4.0-rc.1/angular.js:15673:23)
at HTMLButtonElement.<anonymous> (https://code.angularjs.org/1.4.0-rc.1/angular.js:22924:23)
at HTMLButtonElement.jQuery.event.dispatch (http://localhost:3604/js/lib/jquery/jquery.js:4435:9)
at HTMLButtonElement.jQuery.event.add.elemData.handle (http://localhost:3604/js/lib/jquery/jquery.js:4121:28)
This is my service
this.getBubbleUsers = function (bubbleId) {
var deferred = $q.defer();
$http(
{
method: 'get',
url: baseUrl + "/api/bubble/" + bubbleId + "/users",
headers: { "Authorization": RaqtGlobal.getAuthToken().Authorization }
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
};
I can see that my bubble-service.js is loaded on page but i cannot find out why i cannot access that method - why it say its not a function??
Is it something that it is loaded inside a view from ut-router i cannot call it??

As you are injected your BubblesService to forth parameter so in function it should be in 4th place,
Controller
(function() {
'use strict';
angular
.module('raqtApp')
.controller('BubblesSettingsController', BubblesSettingsController);
BubblesSettingsController.$inject = ['$scope', '$rootScope', '$stateParams', 'BubblesService', '$state'];
function BubblesSettingsController($scope, $rootScope, $stateParams, BubblesService, $state) {
//..your code..//
}
})();

Related

Controller doesn't see function

This is my services.js
(function () {
var app = angular.module('crmService', []);
app.factory('timeline', ['$http', function ($http) {
var _addTimelineEvent = function (clientId, eventData) {
callback = callback || function () {};
return $http({
method: 'POST',
url: '/simple_crm/web/api.php/client/' + clientId + '/timeline',
data: eventData
});
};
return {
addTimelineEvent: _addTimelineEvent
};
}]);
})();
And this is my controller:
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/clients', {
controller: 'ClientsListCtrl',
templateUrl: 'views/clients-list.html'
})
.when('/clients/:clientId', {
controller: 'ClientDetailCtrl',
templateUrl: 'views/client-details.html'
})
.otherwise({
redirectTo: '/clients'
});
$locationProvider.html5Mode(true).hashPrefix('');
}]);
app.controller('ClientDetailCtrl', ['$scope', 'clients', 'users', 'sectors', '$routeParams', '$timeout', 'timeline',
function ($scope, clients, users, sectors, $routeParams, $timeout, timeline) {
$scope.client = {};
$scope.timeline = [];
$scope.timelineEvent = {};
$scope.eventTypes = timeline.getEventsType();
$scope.saveClientData = function () {
if ($scope.clientForm.$invalid)
return;
clients.updateClient($scope.client.id, $scope.client)
.then(
function () {
//messeges to user
},
function (error) {
console.log(error);
}
);
};
$scope.addEvent = function () {
if ($scope.eventForm.$invalid)
return;
timeline.addTimelineEvent($scope.client.id, $scope.timelineEvent)
.then(
function () {
//messeges to user
},
function (error){
console.log(error);
});
};
}]);
})();
And I get an error:
TypeError timeline.addTimelineEvent is not a function
I am not able to understand why the function that is above works fine but timeline.addTimelineEvent, which is virtually identical, reports an error.
Any advice?
I added all code for better view :
Full code
The timeline function is located at the end of the app file

Angular route does not resolve service

I've been scratching my head over this one for a couple hours now, and after a good amount of searching I haven't found a helpful solution.
As the title state, my dependencies are not being resolved by Angular's route provider. This is the error:
Unknown provider: testServiceProvider <- testService <- testService
My compiled Javascript file (app.js) looks like this:
'use-strict';
var app = angular.module('test-app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
testService: function (testService) {
console.log(testService.message);
}
}
})
}]);
app.factory('apiService', ['$http', function ($http) {
function url(endpoint) {
return '/api/v1' + endpoint;
}
return {
user: {
authenticated: function () {
return $http({method: 'GET', url: url('/user/authenticated')});
},
login: function (token) {
return $http({method: 'GET', url: url('/user/login'), cache: false, headers: {
Authorization: 'Basic ' + token
}});
},
logout: function () {
return $http({method: 'GET', url: url('/user/logout')});
},
model: function () {
return $http({method: 'GET', url: url('/user/data')});
}
}
};
}]);
app.factory('testService', function () {
return {
message: 'Hello world'
};
});
app.controller('HomeController', ['$scope', '$http', function ($scope, $http, apiService, testService) {
$scope.user = {
authenticated: false,
error: '',
username: '',
password: ''
};
$scope.login_button = 'Log in';
$scope.isAuthenticated = function () {
return $scope.user.authenticated;
}
$scope.needsAuthentication = function () {
if (!$scope.user.authenticated) {
return true;
}
return false;
}
$scope.logIn = function ($event) {
$event.preventDefault();
$scope.login_button = 'Please wait...';
var token = btoa($scope.user.username + ':' + $scope.user.password);
apiService.user.login(token).then(function (success) {
$scope.user = success.data.user;
$scope.user.authenticated = true;
}, function (error) {
$scope.user.error = 'Please try logging in again.';
$scope.login_button = 'Log in';
});
};
}]);
As far as I can tell, everything should be resolving fine; am I missing or misunderstanding something?
I think the problem in an alias. You use testService as alias for your resolving. $injector could be confused. Try to rename it for example:
resolve: { testData: function (testService) { console.log(testService.message); } }
and rename it in controller as well.
You have to inject the service,
change
From:
app.controller('HomeController', ['$scope', '$http', function ($scope, $http, apiService, testService)
To:
app.controller('HomeController', ['$scope', '$http','apiService','testService' ,function ($scope, $http, apiService, testService)

AngularJS ui-router resolve is undefined

I have moved from using ngRoute to ui-router. I am trying to resolve a Factory call in the route for use in the controller but it is undefined when output to the console. Here is the Factory:
'use strict';
angular.module('angular10App')
.factory('AirportService', function ($http) {
return {
getAirports: function () {
var airports = $http.get('../json/airports.json')
.then(function (response) {
console.log(response.data); //Outputs an array of objects
return response.data;
});
}
});
Here is the Route:
'use strict';
angular.module('angular10App')
.config(function ($stateProvider) {
$stateProvider
.state('selectFlights', {
url: '/select_flights',
templateUrl: 'app/selectFlights/selectFlights.html',
controller: 'SelectFlightsCtrl',
resolve: {
AirportService: 'AirportService',
airports: function (AirportService) {
return AirportService.getAirports();
}
},
});
});
and here is the controller:
'use strict';
angular.module('angular10App')
.controller('SelectFlightsCtrl', function ($scope, airports) {
$scope.selectedAirport = null;
$scope.airports = airports;
console.log($scope.airports); //undefined
});
Try changing your resolve block to this:
resolve: {
airports: function (AirportService) {
return AirportService.getAirports();
}
}
And modify the getAirPorts function into:
function getAirports () {
// You need to return the $http promise (or in your case, 'var airports');
return $http.get('../json/airports.json')
.then(function (response) {
console.log(response.data); //Outputs an array of objects
return response.data;
});
}

Angular Factor Call not working

I am trying to call the update / put method in the factory which will in turn save the changes on the form to the database via an API call. But I get a console error below. The update function is getting called from the button click fine, but it doesn't call the factory and API from there. What am I missing? Thank you!
I updated my code with the suggestion below but now have this error:
My console error: "Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=%24resourceProvider%20%3C-%20%24resource%20%3C-%20memberUpdate
var securityApp = angular.module('securityApp', ['ngRoute']).
config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'PartialPages/members.html',
controller: 'membersController'
})
.when('/memberDetail/:memberID', {
templateUrl: 'PartialPages/memberDetail.html',
controller: 'memberDetailController'
})
.when('/memberEdit', {
templateUrl: 'PartialPages/memberEdit.html',
controller: 'memberEditController'
});
});
securityApp.factory('memberUpdate', function ($resource) {
return $resource('/api/Members/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
securityApp.controller('memberDetailController', function ($scope, $http, $routeParams, memberUpdate) {
var id = $routeParams.memberID;
$http.get('/api/Members/' + $routeParams.memberID).success(function (data) {
$scope.member = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
})
$scope.update = function () {
memberUpdate.update({ id: id }, $scope.member);
};
});
You need to inject memberUpdate into the controller dependencies.
securityApp.controller('memberDetailController', function ($scope, $http, $routeParams, memberUpdate) {
var id = $routeParams.memberID;
$http.get('/api/Members/' + $routeParams.memberID).success(function (data) {
$scope.member = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
})
$scope.update = function () { // you don't need to pass $scope and memberUpdate since they are already available into the scope
memberUpdate.update({ id: id }, $scope.member);
};
});
$resource is in a different module so you need to include it.
var securityApp = angular.module('securityApp', ['ngRoute', 'ngResource']).
her how you install it https://docs.angularjs.org/api/ngResource

AngularJS pass parameter from Controller to Service

I don't know how to pass data from the controller to the service as method arguments... I need to set in the controller the headers variable which is later added to the service which adds this later on to the http call
controller
angular.module('userControllers', []).
controller('userController', ['$scope', '$q', 'Users', '$location',
function($scope, $q, Users, $location) {
$scope.viewUser = function(userId) {
$location.path('/users/'+userId);
};
$scope.createUser = function () {
$location.path('/users/create');
};
headers = {service:'json',resource:'users'};
$scope.users = Users.query(headers);
$scope.users.$promise.then(function(result){
$scope.users = result;
});
}]);
service
angular.module('userServices', ['ngResource']).
factory('Users', ['$resource', '$q', function($resource, $q){
var factory = {
query: function (headerParams) {
var data = $resource('http://localhost:8080/gateway', {}, {
query: {
method: 'GET',
isArray: true,
headers: headerParams
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
In this setup I'm getting Error: [$injector:unpr] Unknown provider: UserProvider <- User ... not really sure how to fix this one out ...
Later edit : code cleanup... posted full code and new error
TypeError: Cannot read property 'then' of undefined
at new <anonymous> (http://localhost/frontend-pdi-angular-js/js/controllers/users.js:16:38)
at invoke (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:3918:17)
at Object.instantiate (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:3929:23)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:7216:28
at link (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js:913:26)
at nodeLinkFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6648:13)
at compositeLinkFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6039:13)
at publicLinkFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:5934:30)
at boundTranscludeFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6059:21)
at controllersBoundTransclude (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6669:18) <div ng-view="" class="ng-scope">
Later edit #2 : some working code, but using no ngResource whatsoever
angular.module('userControllers', ['userServices']).
controller('userController',
['$scope', '$q', 'Users', '$location', '$http',
function($scope, $q, Users, $location, $http) {
headerParams = {service:'json',resource:'users'};
$scope.users = $http({method: 'GET', url: 'http://localhost:8080/gateway', headers: headerParams, isArray:true}).
success(function(data, status, headers, config) {
$scope.users = data;
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(status);
});
}]);
As others mentioned, you are using a non-existent reference to a provider ($promise) in your code. By simply setting the deferred to $scope.users and then acting on the 'then' of that deferred, you can solve this problem.
You can also simplify it a bit. You are setting the deferred on the $scope object and then you're overwriting that with the resolved value of the deferred. So you can do this instead:
Users.query(headers).then(function(result){
$scope.users = result;
});
if you want to assign the deferred to a separate variable:
var deferred = Users.query(headers);
deferred.then(function(result){
$scope.users = result;
});
angular.module('userControllers', ['userServices']).
controller('userController',
['$scope', '$q', 'Users', '$location',
function($scope, $q, Users, $location) {
headers = {service:'json',resource:'users'};
Users.query(headers).then(function(result){
$scope.users = result;
});
}])
angular.module('userServices', ['ngResource']).
factory('Users', ['$resource', '$q', function($resource, $q){
var factory = {
query: function (headerParams) {
var data = $resource('http://localhost:8080/gateway', {}, {
query: {
method: 'GET',
isArray: true,
headers: headerParams
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
Try this. Your not include the userServices module into the userControllers module and you can omit $scope.users = Users.query(headers); part because if you put this this will call the query method.
replace controller with this code:
angular.module('userControllers', []). controller('userController', ['$scope', '$q', 'Users', '$location', function($scope, $q, Users, $location) {
$scope.viewUser = function(userId) {
$location.path('/users/'+userId);
};
$scope.createUser = function () {
$location.path('/users/create');
};
headers = {service:'json',resource:'users'};
Users.query(headers).$promise.then(function(result){
$scope.users = result;
});
}]);
and factory with this code :
angular.module('userServices', ['ngResource']).
factory('Users', ['$resource', '$q', function($resource, $q){
var factory = {
query: function (headerParams) {
return $resource('http://localhost:8080/gateway', {}, {
query: {
method: 'GET',
isArray: true,
headers: headerParams
}
})
}
}
return {
query: factory.query
}
}]);
i think this will help you.

Resources