AngularJS service returns data from other service

51 views Asked by At

I want to create AngularJS service to return data from another service.

I tried to use this code:

'use strict';

angular.module('angularDjangoRegistrationAuthApp')
  .service('currentUser', function (djangoAuth) {
    var that = this;

    djangoAuth.profile().then(function(data) {
      that.username =  data.username;
    });

    this.getUsername = function() {
      return this.username;
    };
});

But when I tried to get username from controller like this:

$scope.username = currentUser.getUsername();

It was empty.

1

There are 1 answers

1
Md. Mahbubul Haque On

In currentUser service you are setting the username by

that.username =  data.username;

but in this.getUsername method you are returning it with this.username which is not defined. so try changing it to

djangoAuth.profile().then(function(data) {
  this.username =  data.username;
});

if djangoAuth service is getting data with profile method correctly then this code should work

OR you can change following code too:

this.getUsername = function() {
  return that.username;
};