Why angularjs's constant not working with factory - angularjs

I have constant mainApp.constant('baseUrl', 'http://localhost:63760') , i need to use it as default base url for all of my factory. when I inject it to a controller, it's working perfectly, but not working with factory(when factory called by the controller) giving an undefined error. please see my below codes.
app.js
'use strict';
var mainApp = angular.module("mainApp", ["ui.router", "ui.bootstrap"]);
mainApp.constant('baseUrl', 'http://localhost:63760');
factory
mainApp.factory('StudentServices', ['$http', '$rootScope', function ($http, $rootScope, baseUrl) {
return {
GetStudentProfileByPIN: function (param) {
alert(baseUrl);
return $http({
url: baseUrl + '/Api/ApiProfile/GetStudentProfile/' + param,
method: 'POST',
async: false
});
}
};
}]);
controller
mainApp.controller('loginController', function ($scope, $rootScope, $state, $window, StudentServices) {
$scope.user = {};
$scope.login = function () {
StudentServices.GetStudentProfileByPIN($scope.PIN).then(function (response) {
if (response.data.Student != null) {
$window.localStorage.setItem('Student', angular.toJson(response.data));
$window.location.href = "/Profile/#/home";
}
else {
alert(response.data.Message);
}
});
};
});

You are missing **'baseUrl',**You should have it as,
mainApp.factory('StudentServices', ['$http', '$rootScope','baseUrl', function ($http, $rootScope, baseUrl) {

inject the string baseUrl too
mainApp.factory('StudentServices', ['$http', '$rootScope','baseUrl' function ($http, $rootScope, baseUrl)

Related

In angularJS, How to refactor an $http call into a Service?

I tried to put the below code into a service but I seem to be missing something! I have to click the button twice to update the list shown in the table:
$scope.todoList = [];
$scope.showTodoList = function(){
var url = '/api/v1/todo/list/'+$scope.report.from+'/'+$scope.report.to;
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
$scope.todoList = response.data;
}, function errorCallback(response) {
console.log(response);
});
}
So I tried to do this:
angular.module('ReportController', []).controller('ReportController', ['$scope', '$http', '$rootScope', '$location', '$localStorage', '$routeParams', 'Report', 'Todo',
function ($scope, $http, $location, $localStorage, $routeParams, Report, Todo) {
$scope.todoList = [];
$scope.showTodoList = function(){
$scope.todoList = Report.getList($scope.report.from, $scope.report.to);
}
}]);
then i created a module and added the factory there and loaded this module with all others
angular.module('ReportService', []).factory('Report', ['$q', '$filter', '$http', '$timeout', function ($q, $filter, $http, $timeout) {
var list;
function getList(date_from, date_to){
var url = '/api/v1/todo/list/'+date_from+'/'+date_to;
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
list = response.data;
}, function errorCallback(response) {
console.log(response);
});
return list;
}
return {
getList: getList
};
}]);
Your problem seems to be that you are not waiting for the callback of $http call when returning the list.
You should make the ReportService's getList function to return a callback or a Promise. It will also change a bit how you need to handle the function call in your ReportController.
Example how to do this with callbacks:
ReportService:
angular.module('ReportService', []).factory('Report', ['$q', '$filter', '$http', '$timeout', function ($q, $filter, $http, $timeout) {
var list;
function getList(date_from, date_to, callback){
var url = '/api/v1/todo/list/'+date_from+'/'+date_to;
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
list = response.data;
return callback(list);
}, function errorCallback(response) {
console.log(response);
return callback(null);
});
}
return {
getList: getList
};
}]);
ReportController:
angular.module('ReportController', []).controller('ReportController', ['$scope', '$http', '$rootScope', '$location', '$localStorage', '$routeParams', 'Report', 'Todo',
function ($scope, $http, $location, $localStorage, $routeParams, Report, Todo) {
$scope.todoList = [];
$scope.showTodoList = function(){
Report.getList($scope.report.from, $scope.report.to, function(res){
if(res) {
$scope.todoList = res;
}
});
}
}]);

Angularjs error issue

I am getting an error TypeError: Cannot read property 'get' of undefined.i have tried so many ways but not able to solve.
mycode is login.controller.js
(function () {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService'];
function LoginController($location, AuthenticationService, FlashService) {
var vm = this;
vm.login = login;
(function initController() {
// reset login status
AuthenticationService.ClearCredentials();
})();
function login() {
var usename=vm.username;
var password=vm.password;
vm.dataLoading = true;
$http.get('http://localhost:8080/ProjectManagement/REST/Login/Check?usename='+usename+'&password='+password+'').success(function(data, status, headers, config,response){
if (data=="0")
{
}
else
{
}
}).error(function(data, status, headers, config,response) {
});
};
}
})();
You missed to add $http dependency inside you controller, make sure all the dependencies are injected before using it.
Code
LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService', '$http'];
function LoginController($location, AuthenticationService, FlashService, $http) {

Can't find out why i'm getting an injector error

I am getting an error on injecting my collections factory, but can't figure out where I went wrong:
Error: [$injector:unpr] http://errors.angularjs.org/1.3.0/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20collections
'use strict';
var thangular = angular.module('thangular', ['ngAnimate']);
thangular.config(function ($interpolateProvider,$httpProvider) {
$interpolateProvider.startSymbol('[[').endSymbol(']]');
$httpProvider.defaults.useXDomain = true;
});
thangular.factory('collections', ['$scope', '$http', '$q',
function ($scope, $http, $q) {
return {
all: function () {
var deferred = $q.defer();
var request = $http({
method: 'GET',
url: '/collections.json',
});
request
.success(function (result) {
deferred.resolve(result.content);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
};
}
]);
thangular.controller('mainCtrl', ['$scope', 'collections',
function ($scope, collections) {
collections.all().then(function (data) {
console.log(data);
});
}
]);
I suppose you shouldn't inject $scope in factory declaration. Just change
thangular.factory('collections', ['$scope', '$http', '$q',
to
thangular.factory('collections', ['$http', '$q',
Factory declaration should not dependent upon controllers $scope.

Calling a function from controller1 within controller2 in angularjs

I have a controller that updates my awards scope:
Controller 1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
})
}
}])
Controller 2
I have another controller 2 with a click event thats outside of this controllers scope. Is it possible for the controller below to call the $scope.updateAwardScope function from controller 1?
.controller('MainController', function ($rootScope, $scope) {
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});
I've found the use of the factory/service pattern to be a very effective way of reusing code in angular applications. For this particular case you could create an AwardFactory, inject it in your controllers and then call the update function. i.e
AwardFactory
myApp.factory('AwardFactory', ['TokenRestangular', function(TokenRestangular.all) {
var factory = {
awards: []
};
factory.update = function() {
resource = TokenRestangular.all('award');
resource.getList().then(function (awards) {
factory.awards = awards;
});
return factory.awards; // You can skip the return if you'd like that
};
return factory;
}]);
YourController
.controller('MainController', function ($rootScope, $scope, AwardFactory) {
$scope.updateAwardScopeClick = function () {
AwardFactory.update();
}
});
Hope it helps!
You can use angular broadcast and receive
Controller1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
$rootScope.broadcast("update.awards");
})
}
}])
Controller 2
.controller('MainController', function ($rootScope, $scope) {
$rootScope.$on('update.awards', function(){
$scope.updateAwardScopeClick();
});
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});

promise is not resolved at controller injection

I'm facing an issue. I'm working with angular 1.2RC3 and ui-route 0.2.
If i resolve with a function which is doing a synchronous return, it works.
With a promise, the controller is initialized before resolving the promise.
http://plnkr.co/edit/feXHNaGsXwpXDBXkxLZx
angular.module('srcApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
var userResult = {
id : 'userid',
displayName : 'displayName'
};
var getUserPromise = function ($q, $timeout, $log) {
var defer = $q.defer;
$timeout(function () {
$log.log('promise resolved');
defer.resolve(userResult);
}, 2000);
return defer.promise;
};
$stateProvider.state('test', {
url: '/',
template: '<div>{{user.displayName}}</div>',
controller: 'testCtrl',
resolve : {
user: getUserPromise
}
});
});
var testCtrl = angular.module('srcApp').controller('testCtrl', function ($scope, $http, $log, user) {
$log.log("test controller init");
$log.log("test controller user=" + user);
$scope.user = user;
});
Weird... It's pretty much what I do line for line in an app.
Solved: http://plnkr.co/edit/oC5wK8aDcq82mWl8ES6l?p=preview
You typed:
$q.defer
instead of:
$q.defer()

Resources