not able to pass data to a data object in angularjs - javascript

N.B: I'm pretty much new to angularJS programming. What I'm trying to do is, to save info returned by a service to an object. My object looks like this.
var userObject = {
"id": "1",
"firstName": "Amelia",
"lastName": "Earheart"
};
I have a factory that returns data from back end and it looks like this:
.factory('myService', function($http) {
var baseUrl = 'backendservice/';
return {
myInfo:function() {
return $http.get(baseUrl + 'getmyInfo');
}
};
})
And this is how my Controller communicates with the factory service:
.controller('myController', function($routeParams,myService) {
var my = this;
my.basicInfo = function () {
//to get my info
myService.myInfo().success(function(data) {
my.activeUser.myData.id = data.id;
my.activeUser.myData.firstName = data.firstName;
my.activeUser.myData.lastName = data.lastName;
});
};
my.addSomething = function(post) {
var userObject = my.basicInfo();
};
});
and this is how I assign the data to userObject
var userObject = my.basicInfo();
I don't know why it's not working. Factory service runs but the value is not assigned to userObject.
My Controller as whole looks like this:
(function() {
angular
.module('myApp.spa', [])
.factory('myService', function($http) {
var baseUrl = 'backendservice/';
return {
myInfo:function() {
return $http.get(baseUrl + 'getmyInfo');
}
};
})
.controller('myController', function($routeParams,myService) {
var my = this;
my.basicInfo = function () {
//to get my info
myService.myInfo().success(function(data) {
my.activeUser.myData.id = data.id;
my.activeUser.myData.firstName = data.firstName;
my.activeUser.myData.lastName = data.lastName;
});
};
my.addSomething = function(post) {
var userObject = my.basicInfo();
};
});
})();

Your function my.basicInfo() does not return anything so the value of your variable userObject is undefined. Also if you want to use userObject on view expose it on your controller instance as my.userObject.
If you want to assign a value to userObject, do it either within the success callback of my.basicInfo() method or return a promise from the method my.basicInfo() and assign the value in then callback of the promise
Approach 1
my.basicInfo = function () {
//to get my info
var activeUser = {};
return myService.myInfo()
.then(function(response) {
angular.extend(activeUser, response.data);
my.userObject = activeUser;
});
};
Approach 2
my.basicInfo = function () {
//to get my info
var activeUser = {};
return myService.myInfo()
.then(function(data) {
angular.extend(activeUser, response.data);
return activeUser;
});
};
my.addSomething = function(post) {
my.basicInfo()
.then(function (response) {
my.userObject = response;
});
};

Reason is my.basicInfo does not return anything and also from $http.success/failure, you can not return any value.
So in this case, following steps you would have to do:
Define var userObject at the top of your controller so that can be accessible to all the methods.
Assign data to userObject inside success callback of $http
(function() {
angular
.module('myApp.spa', [])
.factory('myService', function($http) {
var baseUrl = 'backendservice/';
return {
myInfo:function() {
return $http.get(baseUrl + 'getmyInfo');
}
};
})
.controller('myController', function($routeParams,myService) {
var my = this;
var userObject;
my.basicInfo = function () {
//to get my info
myService.myInfo().success(function(data) {
my.activeUser.myData.id = data.id;
my.activeUser.myData.firstName = data.firstName;
my.activeUser.myData.lastName = data.lastName;
userObject = data;
});
};
my.addSomething = function(post) {
my.basicInfo();
};
});
})();

.factory('UserInfo', function($resource, apiHost) {
return $resource(apiHost + '/userinfo/:userId');
});
.controller('myController', function($routeParams,UserInfo) {
var vm = this;
// suppose that you have stored the userId somewhere after the login
vm.userObject = {};
var myUserInfo = UserInfo.get({
userId: userId
});
vm.refreshData = function (){
myUserInfo.$promise
.then(function(response) {
vm.userObject = response;
}, function(error) {
// doSomething
});
};
vm.update = function(){
myUserInfo.save(vm.userObject, function() {
// console.log('success');
}, function(error) {
// console.log('error');
});
};
});

Related

AngularJS service does not return value from http.get

can someone help me with this code? I have problem with return value, function in controller return only
var products = {"id": 3};
I want to collect value from http.get, can someone tell me how to do that??
Controller:
$scope.product = {};
$scope.init = function () {
$scope.loadProducts()
}
$scope.loadProducts = function () {
// $http.get("/products/list").then(function (resp) {
// $scope.products = resp.data;
// })
$scope.products = getListProducts.loadProducts();
}
Service
var myServices = angular.module('myServices', []);
myServices.service('getListProducts', ['$http', function ($http) {
var products = {"id": 3};
this.loadProducts = function () {
$http.get("/products/list").then(function (resp) {
products = resp.data;
})
return products;
}
}]);
you are returning products before http success , instead use promises and resolve when http success
$scope.product = {};
$scope.init = function () {
$scope.loadProducts()
}
$scope.loadProducts = function () {
// $http.get("/products/list").then(function (resp) {
// $scope.products = resp.data;
// })
$scope.productPromise = getListProducts.loadProducts();
productPromise..then(function (resp) {
$scope.products = resp.data;
});
}
Service
var myServices = angular.module('myServices', []);
myServices.service('getListProducts', ['$http', function ($http) {
var products = {"id": 3};
this.loadProducts = function () {
return $http.get("/products/list");
}
}]);
Make use of promises to enforce serialization of your async code.
Refactor your service method as:
this.loadProducts = function () {
var getProducts = new Promise(function(resolve,reject){
$http.get("/products/list").then(function (resp) {
resolve(resp.data);
})
});
return getProducts;
};
And your Controller method as:
getListProducts.loadProducts().then(function(data){
//success callback
$scope.products = data;
});
You can provide the error callbacks as well.
Hope this helps !
You should use promises to return values from your service.
You can use $q in your service. It would help functions to run asynchronously.
myServices.service('getListProducts', ['$http','$q', function ($http,$q) {
var products = {"id": 3};
this.loadProducts = function () {
var deferred = $q.defer();
$http.get("/products/list").then(function (resp) {
products = resp.data;
deferred.resolve(products);
},function(error){
deferred.reject(error);
});
return deferred.promise;
}
}]);
And Your method in controller should handle success and error callbacks :
$scope.loadProducts = function () {
getListProducts.loadProducts().then(function(response){
$scope.products=response;
},function(error){
//your processing logic
});
}
I hope this would help you.

jasmine testing a mock service in an angular 1.5 controller

Given the following test.
How do I ensure that the promise is resolved, and the data is provided.
describe("component: FicaStatusComponent",
function () {
var fs;
beforeEach(function () {
module("aureus",
function ($provide) {
$provide.service("ficaService", function () {
this.status = function () {
return $q(function (resolve, reject) {
resolve([{ documentType: { id: 1 } }]);
});
}
})
});
});
beforeEach(inject(function (_$componentController_, _ficaService_) {
$componentController = _$componentController_;
fs = _ficaService_;
}));
it("should expose a `fica` object", function () {
console.log('should expose');
var bindings = {};
var ctrl = $componentController("ficaStatus", null, bindings);
expect(ctrl.fica).toBeDefined();
});
it("compliant with no documents should not be compliant",
function () {
var ctrl = $componentController("ficaStatus");
expect(ctrl.fica.length).toEqual(1);
});
}
);
The second test compliant with no documents... is failing. The length is zero. The other test is passing, so I have the correct controller being instantiated, the property is defined.
The mock service is not resolving the data correctly, probably because the Promise is still executing, or not being called at all.
Here is the implementation of the controller for the component:
var FicaStatusController = (function () {
function FicaStatusController($log, $loc, ficaService) {
var _this = this;
this.$log = $log;
this.$loc = $loc;
this.ficaService = ficaService;
this.fica = [];
this.ficaService.status(1234).then(function (_) { return _this.fica = _; });
}
The service is as follows:
var FicaStatusService = (function () {
function FicaStatusService($log, $http) {
this.$log = $log;
this.$http = $http;
}
FicaStatusService.prototype.status = function (accountNumber) {
var url = "api/fica/status/" + accountNumber;
this.$log.log("status: " + url);
return this.$http
.get(url)
.then(function (_) { return _.data; });
};
return FicaStatusService;
}());
...
First, u can use $q like:
this.status = function () {
return $q.when([{ documentType: { id: 1 } }]);
}
Second, to resolve promise use $scope.$digest, $rootScope.$digest:
var a = $q.when({test: 1});
expect(a.test === 1).toBe(false);
$rootScope.$digest();
expect(a.test === 1).toBe(true);

Struggling to return result to scope from factory

I'm trying to return the filtered object from a factory. At the point of "return getTheChosen" the object is as expected. I can't assign it to my $scope.postDetail!
Any advice appreciated!
app.factory('postsFactory', function ($http) {
var response = $http.get('http://myjsonendpoint.com/');
var factory = {};
factory.list = function () {
return response;
};
factory.get = function (id) {
var getTheChosen = factory.list().then(function (res) {
var chosen = _.find(res.data, {'id': id});
return chosen;
});
return getTheChosen;
};
return factory;
});
then...
app.controller('ThoughtsController', function ($scope, postsFactory) {
postsFactory.list()
.then(function (data) {
$scope.posts = data;
});
});
then...
app.controller('PostDetailController', function ($scope, postsFactory, $routeParams) {
$scope.postDetail = postsFactory.get(parseInt($routeParams.postId));
$scope.test = 'yep';
});
Do it another way in your PostDetailController:
postsFactory.get(parseInt($routeParams.postId)).then(function(data) {
$scope.postDetail = data;
});
Instead of:
$scope.postDetail = postsFactory.get(parseInt($routeParams.postId));
Hope this will work

Passing Object from factory to the controller

I am trying to create a factory that makes an ajax request to some API and then returns an object of data. My code is:
app.factory('Test', function($http, $q) {
var data = {response:{}};
var getMessages = function() {
$http.get('https://someapi.com').then(
function(jsonAPI) {
var dataObj = {};
var messages = [];
$.each(jsonAPI.data.data, function(x, data) {
dataObj[x] = data;
$.each(jsonAPI.data.included, function(y, included) {
if(data.relationships.sender.data.id == included.id) {
dataObj[x].sender = included;
}
});
messages.push(dataObj[x]);
});
data.response = messages;
},
function(errorResponse) {
// todo handle error.
}
);
};
getMessages();
return {
data
};
});
However when I try to remove the 'response' attribute from the data object that is created and have data = messages instead of data.response = messages the data object is not getting filled. If I keep the response attribute then in my controller when I try to console.log(Test.data['response']) I get an empty object. console.log(Test.data) returns a valid object though. What am I missing here?
If you want to keep data stored in factory you can store the promise returned by $http and have that promise resolve with the stored data.
app.factory('Test', function($http, $q) {
var data = null, dataPromise = null;
function getMessages() {
if (!dataPromise) {
dataPromise = $http.get('https://someapi.com').then(
function (jsonAPI) {
var dataObj = {};
var messages = [];
$.each(jsonAPI.data.data, function (x, data) {
dataObj[x] = data;
$.each(jsonAPI.data.included, function (y, included) {
if (data.relationships.sender.data.id == included.id) {
dataObj[x].sender = included;
}
});
messages.push(dataObj[x]);
});
data = messages;
return data;
},
function (errorResponse) {
// todo handle error.
}
);
}
return dataPromise
}
return {
getMessages : getMessages
};
});
then in any controller or directive or resolve:
Test.getMessages().then(function(messages){
$scope.messages = messages;
});

AngularJS: could not access Object property in the controller

this is my object that get from a service.
this is my controller.
var user = useroneService.getLoggedUser(user);
console.log(user);
console.log(user.data);
I got a undefined when I try to access the data. How do I access to the Object data?
user.service.js
'use strict';
angular.module('app').service('userService',['authService', 'userTransformer','LoggedUser', function(authService, userTransformer, LoggedUser) {
this.getLoggedUser = function(user){
return authService.login(user).then(function (response) {
var loggedUser = userTransformer.transform(response.data);
});
};
}]);
logged.user.js
angular.module('app').value('LoggedUser', function () {
var LoggedUser = function () {
this.dispalyName = '';
this.token = '';
this.logged = false;
};
LoggedUser.prototype = {
};
});
user.transformer.js
angular.module('app').factory('userTransformer',['LoggedUser', function (LoggedUser) {
//logged user transform
var transformObject = function (response) {
var model = new LoggedUser();
angular.extend(model, response);
return model;
};
return {
transform: transformObject
};
}]);
flow
AuthService(get data)==>UserService(data transform to LoggedUser using the transformer)
==>LoginController
You are not returning a promise. Change your controller code to:
useroneService.getLoggedUser(user).then(function(data) {
var user = data;
console.log(user);
})
One more thing, you are not returning the response from your service:
return authService.login(user).then(function (response) {
var loggedUser = userTransformer.transform(response.data);
return loggedUser; //add this
});

Categories

Resources