1
getTopicContent.request().finally(function(){
    $scope.loader= false;
}).then(function(response){
    $scope.threadContent = response.data;


})


$scope.loadPages = function($scope) {
    console.log($scope.threadContent.totalPages);
}

It returned threadContent of undefined. getTopicContent is the service, but I expect $scope.threadContent can be shared with $scope.loadPages function?

mike19911
  • 101
  • 1
  • 7

1 Answers1

1

Since you are loading content asynchronously, you can't expect data to be available in synchronous manner. loadPages function should rely on promis resolution before accessing data. For example you can rewrite you code this way:

function getContent() {
    return getTopicContent.request().then(function (response) {
        return response.data;
    }).finally(function () {
        $scope.loader = false;
    });
}

$scope.loadPages = function ($scope) {
    getContent().then(function(data) {
        $scope.threadContent = data;
        console.log($scope.threadContent.totalPages);
    });
}

Also read this related problem description.

Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • I got an undefined is not a function error with your code. – mike19911 Dec 06 '14 at 08:38
  • Sorry, typo. It should be `getContent().then`. Updated code in answer. – dfsq Dec 06 '14 at 08:39
  • the flow and concept that you suggested make sense but I wonder why it says undefined function. – mike19911 Dec 06 '14 at 08:40
  • Because the code I posted was `getContent.then(...)` while it should be `getContent().then(...)`. Just try updated code in the answer. – dfsq Dec 06 '14 at 08:42
  • but I'm getting this TypeError: Cannot read property 'threadContent' of undefined – mike19911 Dec 06 '14 at 08:44
  • Just a thought: Shouldn't it be `return getTopicContent.request();` request() is returning the promise object, so you don't need then() on both getTopicContent.request() _and_ getContent(). The change being that the then/finally logic you have inside getContent() would be inside loadPage(). Not sure if that's desirable for what you're looking to do though. – macinnir Dec 06 '14 at 08:53
  • Ops, the problem is that I forgot to return data from `then`. See updated code for better approach. – dfsq Dec 06 '14 at 09:05