Pass data from service to controller in angularjs - javascript

Following is my Service code -
myApp.service('loginServiceChk', function(){
this.getInfo = {};
this.chkLogin = function($http,$location,$window){
$http.get('/users/chklogin')
.success(function (data, status, headers, config) {
if (data.code!="200"){
this.getInfo = {};
$window.location.href='/#/users/login';
}else{
this.getInfo = data.usersession;
}
});
};
});
My controller code -
myApp.controller('userDash',function($scope,$http,$location,loginServiceChk,$window){
loginServiceChk.chkLogin($http,$location,$window);
console.log(loginService.getInfo);
$scope.userLogout = function() {
$http.get('/users/logout').success(function (data, status, headers, config) {
if (data.logout=="200"){
merInfo = {} ;
$window.location.href='/#/userss/login';
}
})
};
});
However I am always getting an empty object in the console ( console.log(loginService.getInfo); ) . Let me know what I am doing wrong here.
I am expecting session data in the this.getInfo.
EDIT
If I am using .then then it is going in the if ie if (data.code!="200"){ here.

You have to wait for the promise.
Use this in your controller:
loginServiceChk.chkLogin($http,$location,$window).then(function() {
console.log(loginService.getInfo);
});
And add return to your service:
this.chkLogin = function($http,$location,$window){
return $http.get('/users/chklogin')
.then(function (data, status, headers, config) {
if (data.code!="200"){
this.getInfo = {};
$window.location.href='/#/users/login';
}else{
this.getInfo = data.usersession;
}
});
};

Related

ReferenceError: angular is not defined?

I have create service that are interact with server side but my case error like
angular are not defined. I am tired this error.
(function() {
angular.module('myApp').factory('userService', function($http, $q, $rootScope,CONSTANTS) {
var obj = {};
var response = {};
obj.setResponse = function(data) {
response = data;
}
obj.getResponse = function() {
return response;
obj.saveUser = function(user) {
console.log(user);
console.log()
var deferred = $q.defer();
var config = {
headers : {
'Content-Type' : 'application/json'
}
}
var data = angular.toJson(user);
console.log(data);
$http.post("user/createUser", data, config).success(
function(data, status, headers, config) { deferred.resolve(data);
}).error(function(data, status, headers, config) {
deferred.reject();
});
return deferred.promise;
}
return obj;
});
})();

How to get value of javascript array out of factory/services in angularjs

The scope of array 'chats' is limited only upto '.then' and gives its value null inside 'all' function
angular.module('starter.services', [])
.factory('Chats', function($http) {
var chats=[];
result = "";
$http.get('http://localhost/Finalvts/AndroidData/GetDailySchedule.php')
.success(function(data, status, headers,config){
console.log('data success');
console.log(data); // for browser console
var i=0;
data.forEach(function (x) {
x['id']=i;
i++;
})
chats = data; // for UI
console.log(chats);
})
.error(function(data, status, headers,config){
console.log('data error');
})
.then(function(result){
chats = result.data;
console.log(chats);
});
return {
all: function() {
console.log(chats);
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
};
});
An array chats doesn't shows the value returned by variable 'data' in console...Please give some suggestions... Thank You...
You return chats before fetching the data from http request. This is because $http.get is asynchronous and it takes certain time to fetch data. While this is fetching data you are returning the chats data which currently have []. Try returning data in .then(). Something like this
angular.module('starter.services', [])
.factory('Chats', function($http) {
var chats = [];
result = "";
$http.get('http://localhost/Finalvts/AndroidData/GetDailySchedule.php')
.success(function(data, status, headers, config) {
console.log('data success');
console.log(data); // for browser console
var i = 0;
data.forEach(function(x) {
x['id'] = i;
i++;
})
chats = data; // for UI
console.log(chats);
})
.error(function(data, status, headers, config) {
console.log('data error');
})
.then(function(result) {
chats = result.data;
console.log(chats);
return {
all: function() {
console.log(chats);
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
};
});
});

Connecting a promise through two services

I'm a bit new to angular and am trying to understand how I can use a promise with two services.
In the code below in the App.js I call FirstService.get(), which should wait for the RestService to return the result. In the App.js I would like to use the .then() to wait for the result from FirstService.get().
My question how do I need to set up the promise in the First Service so that I can use the .then() in the App.js?
Thanks!
// App.js
FirstService.get().then(function(promise) {
// do something here with the result
}, function(response) {
console.log('error');
});
//First Service
oApp.service( 'FirstService', function( RestService, $localStorage, $q ) {
this.get = function( ) {
var url = o.buildServerUrl();
// Retrieve info
RestService.get(url, function(response) {
return response;
});
};
});
// Rest Service
oApp.service( 'RestService', function( $rootScope, $http ) {
this.get = function ( url, callback ) {
try {
$http.get(url).
success(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
}).
error(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
});
}
catch(err) {
var response = o.createExceptionResponse(err.message);
callback(response);
}
}
});
This should do it:
// App.js
FirstService.get().then(function(promise) {
// do something here with the result
}, function(response) {
console.log('error');
});
//First Service
oApp.service( 'FirstService', function( RestService, $localStorage, $q ) {
this.get = function( ) {
var deferred = $q.defer();
var url = o.buildServerUrl();
// Retrieve info
RestService.get(url, function(response) {
deferred.resolve(response);
});
return deferred.promise;
};
});
// Rest Service
oApp.service( 'RestService', function( $rootScope, $http ) {
this.get = function ( url, callback ) {
try {
$http.get(url).
success(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
}).
error(function(data, status, headers, config) {
var response = o.processServerResponse(data, status);
callback(response);
});
}
catch(err) {
var response = o.createExceptionResponse(err.message);
callback(response);
}
}
});

How to returning data from a resource using angular

I'm creating service layers to interact with Rest server, but I've got some problems with ngResource promises.
var grupogestion= angular.module('app.grupogestion.services', ['ngResource']);
grupogestion.factory('Grupogestion', ['$resource', function ($resource){
return $resource('api/grupogestiones/:action/:id.:format',
{
action: '#action', id:'#id', format:'json'
},
{
'get': {method:'GET'},
'post': {method:'POST',headers : {'Content-Type': 'application/x-www-form-urlencoded'}},
'save': {method: 'POST',headers : {'Content-Type': 'application/x-www-form-urlencoded'}}
}
);
}]);
grupogestion.service('GrupogestionService',['Grupogestion', function (Grupogestion){
this.findAll = function (){
Grupogestion.get({action: 'index'},function (data, status, headers, config){
return data;
});
}
this.save = function (grupogestion){
Grupogestion.save({'action':'add'},$.param(grupogestion)).$promise.then(
function(data){
alert('k');
return data;
},
function(error){
alert('j');
return error;
}
);
}
}]);
When I call var response = GrupogestionService.save(data) from angular controller, I don't get the data at the same time I call the function, so the question is: How can I modify GrupogestionService for returning data to the controller?
I've tried to return the promise but I couldn't do it. Thanks for helping.
// service code
grupogestion.service('GrupogestionService', ['Grupogestion', function (Grupogestion) {
this.findAll = function () {
Grupogestion.get({action: 'index'}, function (data, status, headers, config) {
return data;
});
};
this.save = function (grupogestion) {
return Grupogestion.save({'action': 'add'}, $.param(grupogestion));
}
}]);
//run in your controller
var response = GrupogestionService.save(data).$promise.then(
function (data) {
alert('k');
return data;
},
function (error) {
alert('j');
return error;
}
);

AngularJS : Service not Returning Variables to Controllers

My app has a service that is supposed to return an array of objects (tweets from the twitter api) that looks like:
.service('twitterService', function($http) {
this.getTweets = function(){
$http.get('http://example.com/?json=get_twitter_sidebar').success(
function(data, status, headers, config) {
if (data.status == 'ok') {
return data.feed;
} else {
return 'Error Retrieving Feed'
}
});
}
})
This service seems to work; it calls the api and returns the desired object array (I used console.log to verify). However, I can't seem to pass the returned array to my controller:
var TopPageCtrl = function($scope, $window, $http, twitterService) {
$scope.feed = twitterService.getTweets();
};
When I use console.log($scope.feed), it returns undefined. I've tried a million approaches but nothing seems to work. What am I doing wrong?
return the promise
.service('twitterService', function($http) {
this.getTweets = function(){
var p = $http.get('http://example.com/?json=get_twitter_sidebar').success(
function(data, status, headers, config) {
if (data.status == 'ok') {
return data.feed;
} else {
return 'Error Retrieving Feed';
}
});
return p;
}});
var TopPageCtrl = function($scope, $window, $http, twitterService) {
twitterService.getTweets().then(function (response) {
$scope.feed = response;
};};
Maybe it's returning a promise that needs to be resolved? Try something like...
var getFeed = twitterService.getTweets();
getFeed.then(function (feed) {
$scope.feed = feed;
});
$scope.feed = twitterService.getTweets();
this.getTweets = function(){
$http.get('http://example.com/?json=get_twitter_sidebar').success(
function(data, status, headers, config) {
if (data.status == 'ok') {
return data.feed;
} else {
return 'Error Retrieving Feed'
}
});
}
Your function isn´t returning anything, that´s why you are getting "undefined"..
Try this:
this.getTweets = function(){
return $http.get('http://example.com/?json=get_twitter_sidebar').success(
function(data, status, headers, config) {
if (data.status == 'ok') {
return data.feed;
} else {
return 'Error Retrieving Feed'
}
});
}
twitterService.getTweets().then(function (response){...});

Categories

Resources