53285

AngularJs get employee from factory

I've got a employeeController and a employeeFactory in the employeeFactory I receive an employee like this:

function employeeFactory(authenticationFactory,requestFactory,GLOBALS) { var factory = {}; var vm = this; vm.employee = {}; factory.getEmployee = function(id) { data = {"api_token": authenticationFactory.getToken()}; url = GLOBALS.url + 'show/employee/' + id; requestFactory.post(url, data) .then(function (response) { return vm.employee = response.data.result.Employee; }, function () { $window.location.assign('/'); }); } return factory; }

In my controller I'm trying to receive it like this:

console.log(employeeFactory.getEmployee($routeParams.id));

But the result is null?

When I console.log the response in my requestFactory I receive an employee object. What am I doing wrong?

Answer1:

Reason behind it is, you missed to return promise of requestFactory.post from factory.getEmployee method

<strong>Code</strong>

factory.getEmployee = function(id) { data = {"api_token": authenticationFactory.getToken()}; url = GLOBALS.url + 'show/employee/' + id; return requestFactory.post(url, data) .then(function (response) { return vm.employee = response.data.result.Employee; }, function () { $window.location.assign('/'); }); }

But even though you do it, you will not able to get value employee object printed. It will print promise object return by $http.post method/ $resource method

For getting hold on that object you need to use .then function over that promise object. like below

employeeFactory.getEmployee($routeParams.id).then(function(employee){ console.log('Employee', employee) })

Answer2:

We can use deferred api in angularjs for better communication between caller and service.

factory.getEmployee = function(id) { var deferred = $q.defer(); data = {"api_token": authenticationFactory.getToken()}; url = GLOBALS.url + 'show/employee/' + id; return requestFactory.post(url, data) .then(function (response) { deferred.resolve(response.data.result.Employee); }, function () { deferred.reject(); }); return deferred.promise; }

On your controller:

employeeFactory.getEmployee($routeParams.id).then(function(employee){ console.log('Employee', employee) },function(){ $window.location.assign('/'); })

By this approach we can notify caller with some messages if your response gets delayed. For more info see this link. angular promises

Recommend

  • The $scope variable is undefined unless I forced it to retrieve from service again
  • Running Angular2 In Subdirectory
  • save data in json local storage with angularjs
  • Cannot add Foreign Key on tables in DashDB / DB2 on Bluemix
  • Symfony2 Form is always empty after submitting
  • Single Table Inheritance in Rails 4
  • Express displaying mongodb documents in Jade
  • Angular page doesn't refresh after data is added or removed
  • Ajax Upload File: $_FILES is empty but files exists in request header
  • Alert pop up with LWUIT
  • Disabling Alt-F4 on a Win Forms NotifyIcon
  • How to get a value (ex: baseURL) in every Karate feature?
  • How to add date and time under each post in guestbook in google app engine
  • javascript inside java/jsp code
  • Sending data from AppleScript to FileMaker records
  • Perl system calls when running as another user using sudo
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • Numpy divide by zero. Why?
  • php design question - will a Helper help here?
  • Circular dependency while pushing http interceptor
  • Is there a mandatory requirement to switch app.yaml?
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • KeystoneJS: Relationships in Admin UI not updating
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • Free memory of cv::Mat loaded using FileStorage API
  • How to set the response of a form post action to a iframe source?
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Memory offsets in inline assembly
  • Change div Background jquery
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize