I am not able to update my $scope.gs variable in the view using {{gs}} when I am doing http.get in the service. I tried reading some of the answers but they seem to suggest this method. Please help...
My service method is as below:
app.service('myService', function($http, $rootScope) {
this.getData = function(key){
return $http.get('/myapp/stocklist/AMZN').
then(function(data) {
return data;
});
}
//return this;
});
My controller is:
app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService){
myService.getData($scope.mySelected).then(function(codes){
$scope.gs= codes;
});
}]);
I am not sure if I should use factory instead of Service for this. Can you please advice?
possible to use $q
app.service('myService', function($http, $rootScope, $q) {
return {
getData: function (key) {
var deffered = $q.defer();
$http.get('/myapp/stocklist/AMZN')
.then(function (result) {
deffered.resolve(result.data);
}, function (error) {
deffered.reject(error);
});
return deferred.promise
}
}
});
or adjust your service to
app.service('myService', function($http, $rootScope, $q) {
return {
getData: function (key) {
$http.get('/myapp/stocklist/AMZN')
}
}
});
You use then twice. Try
Service
app.service('myService', function($http, $rootScope) {
this.getData = function(key){
return $http.get('/myapp/stocklist/AMZN');
});
});
Controller
app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService){
myService.getData($scope.mySelected).then(function(response){
$scope.gs= response.data;
});
}]);
Related
I'm trying to assign data returned by service to $scope property. Somehow it doesn't work properly. The service method correctly get data via $http.get but then it is not assigned to $scope in the controller.
app.service('StoreService', ['$http', function ($http) {
this.getStoreNamesService = function () {
console.log('getStoreNames called');
$http.get('http://localhost:8080/storys')
.success(function (response, status) {
console.log(response);
return response;
})
};
}]);
app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) {
$scope.storeNames = StoreService.getStoreNamesService();
}]);
Printing the response in service gives correct data. But when I'm printing $scope.storeNames it gives me undefined also on the views there is no data.
app.js:
var app = angular.module('BlankApp', ['ngMaterial', 'ngRoute'])
.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('teal')
.accentPalette('red')
.warnPalette('red');
});
app.config(function ($routeProvider) {
$routeProvider
.when('/addItem', {
templateUrl: 'templates/addItemForm.html',
controller: 'ItemFormController'
})
.when('/', {
templateUrl: 'templates/first.html'
})
.when('/store', {
templateUrl: 'templates/itemsInStore.html',
controller: 'StoreController'
})
.when('/item/:itemId', {
templateUrl: 'templates/itemView.html',
controller: 'ItemController'
})
.otherwise({
template: '<h1>otherwise template</h1>'
})
});
The order of script tags:
<!-- Angular Material requires Angular.js Libraries -->
<script src="js/angular-1.5.8/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.min.js"></script>
<!-- Angular Material Library -->
<script src="js/AngularMaterial/angular-material.js"></script>
<!-- Your application bootstrap -->
<script src="js/app.js"></script>
<script src="js/service/itemService.js"></script>
<script src="js/service/StoreService.js"></script>
<script src="js/controller/testController.js"></script>
<script src="js/controller/SideNavController.js"></script>
<script src="js/controller/ItemFormController.js"></script>
<script src="js/controller/sampleController.js"></script>
<script src="js/controller/ItemController.js"></script>
This should work:
app.service('StoreService', ['$http', function ($http) {
this.getStoreNamesService = function () {
console.log('getStoreNames called');
return $http.get('http://localhost:8080/storys').then(
function success(response, status) {
console.log(response);
return response;
})
};
}]);
app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) {
StoreService.getStoreNamesService().then(function(result){
$scope.storeNames = result;
});
}]);
You can only assign the variable storeNames after the promise is resolved. The way you were doing, the promise was being assigned to the variable.
Also notice that .success() is deprecated. Use .then() instead.
Couple of things you were mistaken
You should return the promise object return by $http method from service method getStoreNames.
You should not be passing $scope(context) to service to modify it.
You should use .then function to get value from promise object.
app.service('StoreService', ['$http', function ($http) {
this.getStoreNamesService = function () {
//return promise here
return $http.get('http://localhost:8080/storys');
};
}]);
Controller
StoreService.getStoreNamesService($scope).then(function(response){
$scope.storeNames = response.data;
});
When using Angular you're better off returning a promise, the $http service returns a promise and you can move the success callback to the scope:
app.service('StoreService', ['$http', function ($http) {
this.getStoreNamesService = function () {
return $http.get('http://localhost:8080/storys');
};
}]);
app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) {
StoreService.getStoreNamesService().then(function (response, status) {
$scope.storeNames = response.data;
});
}]);
Or you can create a deferred object which is similar in that a promise is returned, except it just returns the data and not the $http status codes, etc:
app.service('StoreService', ['$http', '$q', function ($http, $q) {
this.getStoreNamesService = function () {
var deferred = $q.defer();
$http.get('http://localhost:8080/storys').then(function(response, status){
deferred.resolve(response.data);
});
return deferred;
};
}]);
app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) {
StoreService.getStoreNamesService().then(function (data) {
$scope.storeNames = data;
});
}]);
See $q
In both cases the scope object should be populated within the controller.
I tried to call function defined in a service.
var app = angular.module('title', ['flash', 'ngAnimate', 'ngRoute'],
function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
})
.service('getWidgets', function (globalServices, $http) {
var getData = function() {
var getWidgetUrl = globalServices.baseUrl + "admin/widget/list-text-widget";
return $http({method:"GET", url:getWidgetUrl})
.then(function(result){
return result.data;
});
};
return { getData: getData };
});
Calling section
var widget = getWidgets.getData()
.then(function (result) {
$scope.widgets = result;
$scope.$apply();
});
But it return an error getWidgets.getData is not a function.
What would be the root cause?
Change with this:
angular.module('dss')
.controller('widgetCtrl',
['$scope', '$compile', '$window', '$location', '$http', 'globalServices', 'getWidgets', 'Flash', '$timeout', '$sce', '$routeParams', widgetCtrl]);
function widgetCtrl($scope, $compile, $window, $location, $http, globalServices, getWidgets, Flash, $timeout, $sce, $routeParams) {
var widget = getWidgets.getData();
widget.then(
function (result) {
$scope.widgets = result; $scope.$apply();
});
}
EDIT: if you want an advice, use this syntax:
widgetCtrl.$inject = ['$scope', '$compile', '$window', '$location', '$http', 'globalServices', 'getWidgets', 'Flash', '$timeout', '$sce', '$routeParams'];
angular.module('dss').controller('widgetCtrl', widgetCtrl);
function widgetCtrl($scope, $compile, $window, $location, $http, globalServices, getWidgets, Flash, $timeout, $sce, $routeParams) {
var widget = getWidgets.getData();
widget.then(
function (result) {
$scope.widgets = result; $scope.$apply();
});
}
You are using a service and returning an object on its constructor.
Services get initialized as
new yourFunction and factories as yourFunction().
Switch it from service to factory and it will work.
EDIT: If you want to keep using a service, try this.
Note I changed the name of the service
function GetWidgetsService($http, globalServices){
this._$http = $http;
this._globalServices = globalServices;
}
GetWidgetsService.prototype.getData = function() {
var getWidgetUrl = this._globalServices.baseUrl + "admin/widget/list-text-widget";
// Angular $http() and then() both return promises themselves
return this._$http({method:"GET", url:getWidgetUrl}).then(function(result){
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};
angular.module('yourModule').service('getWidgetsService', GetWidgetsService);
EDIT 2: For completeness, here is your fixed factory
angular.module('yourModule').factory('getWidgetsFactory', function ($http, globalServices) {
return {
getData: function () {
var getWidgetUrl = globalServices.baseUrl + 'admin/widget/list-text-widget';
// Angular $http() and then() both return promises themselves
return $http({method: 'GET', url: getWidgetUrl}).then(function (result) {
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
}
};
});
EDIT 3: HERE is a JSBin with your code working with my first solution.
Try this way
.service('getWidgets', function (globalServices, $http) {
return { getData: function() {
var getWidgetUrl = globalServices.baseUrl + "admin/widget/list-text-widget";
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:getWidgetUrl}).then(function(result){
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};
};
});
I need to update view when new data created at server?
How to do this correct?
My controller
app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.success(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
}]);
My factory
app.factory('games', ['$http', function($http) {
return $http.get('./game')
.success(function(data) {
return data;
})
.error(function(data) {
return data;
});
}]);
Remember that services in Angular are objects. So create a simple method that returns a promise, to manage it in the controller.
Controller
app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.get().then(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
}]);
Service
app.service('games', ['$http', function($http) {
this.get = function() {
return $http.get('./game');
};
}]);
you can use $timeout if you do not wish to use websockets
$timeout(function(){
games.success(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
},1000);
Update : sorry it should be $interval
$interval(function(){
games.success(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
},1000);
Update : how to do this using factory
app.factory('games', ['$http', function($http) {
return {
getGame: function() {
return $http.get('./game');
}
}
}]);
Now in your controller
app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.getGame().success(function(data) {
$scope.games = data[0];
});
}]);
Controller Code
'use strict';
angular.module('MyApp').controller('ArticleContribEmailController', [
'$scope', 'ArticleAppState', 'fbsUserDataService', 'contribEmailService',
function ($scope, ArticleAppState, fbsUserDataService, contribEmailService ) {
this.userChanged = function () {
if (fbsUserDataService.initialized && fbsUserDataService.user && ArticleAppState.page_data) {
// user has authenticated.
contribEmailService.initForm();
}
};
// watch for when user data is available, run userChanged.
$scope.$watch(function() { return fbsUserDataService.user; }, this.userChanged);
$scope.$watch(function() { return fbsUserDataService.initialized; }, this.userChanged);
}
]);
Service Code
'use strict';
angular.module('forbesArticleApp').service('contribEmailService', [
'$injector', '$route', 'ArticleAppState', 'fbsUserFormFactory', 'fbsUserDataService',
function initForm ($injector, $route, ArticleAppState, fbsUserFormFactory, fbsUserDataService) {
console.log("Hello world!");
}
]);
I only want to fire the contribEmailService.initForm() function from the call in my controller, but it is firing as soon as the page loads.
How do I set when the service function initForm() is called?
Here is the corrected service code:
'use strict';
angular.module('forbesArticleApp').service('contribEmailService', [
'$injector', '$route', 'ArticleAppState', 'fbsUserFormFactory', 'fbsUserDataService',
function($injector, $route, ArticleAppState, fbsUserFormFactory, fbsUserDataService) {
return {
initForm: function() {
console.log("Hello world!");
}
};
]);
The service function is a factory that will in turn return the actual service. So it will run the first time it is requested as a dependency. The way you had it written, in fact, contribEmailService would have been undefined within your function, because your factory didn't actually return anything.
Hope this helps!
controller:-
blogcontroller is controller name
app.controller('blogController', function($scope, $compile, $http, blogAuth, AppInfo, $location,$element){
$scope.blog_abuse = function(blog_id)
{
blogAuth.BlogAbuse(blog_id).then(function(response)
{
$scope.DetailblogList.is_abused = response.records.is_abused;
},function(error){
});
}
});
service:-
app.factory('AppInfo', function(){
return {
serviceURL:site_url
};
});
app.service('blogAuth', function($http, $rootScope, $q, AppInfo){
this.BlogAbuse = function(blog_id){
var deferred = $q.defer();
var pageObj ={"blog_id":blog_id};
$http.post(AppInfo.serviceURL+'blog/blog_abuse',pageObj).success(function(data){
deferred.resolve(data);
}).error(function(msg, code) {
console.log('error', code, msg );
});
return deferred.promise;
}
});
I have a factory method as..
(function (angular) {
"use strict";
angular
.module('app')
.factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) {
var markCurrentUserAsContentOwner = function () {
var user = getCurrentUser(true);
user.set('isContentOwner',"true");
user.save(null, {
success: function(savedUser) {
alert("succes");
},
error: function(savedUser,error) {
alert("error");
}
});
};
}]);
})(angular);
Now If I call this method from another service method..
(function(angular) {
'use strict';
angular
.module('app')
.service('ContentOwnerService',
[
'$q', 'UserService'
function($q, userService) {
var servicemethod=function() {
userService.markCurrentUserAsContentOwner();//UserService is the factory name
};
}]);
})(angular);
Its showing an error..Uncaught TypeError: undefined is not a function.
Please anyone help me to resolve this error..
Use $injector service to solve this problem.
Example:
session.factory('redirectInterceptor', ['$injector','$rootScope', '$timeout', '$q', '$window', function($injector,$rootScope, $timeout, $q, $window) {
return {
'request': function(req) {
req.headers['CustomHeader'] = "Be Creative!";
return req || $q.when(req);
},
'response': function(response) {
if (response.data.Status === 'Failed...') {
var AuthenticationService = $injector.get('AuthenticationService');
AuthenticationService.ClearCredentials();
$window.location.href = "/#/login";
$timeout(function() {
$rootScope.sessiondata = true;
}, 5000)
return $q.reject(response);
} else {
return response;
}
}
}}])