2017-04-25 74 views
0

您好我有一個問題均可進行該服務服務,其提供一個JSON AngularJS

app.service('myStorage',function($http, $localStorage){ 
this.getFilms = function(){ 
    /* Carga la lista de peliculas de localStorage si existe*/ 
    if ($localStorage.films && $localStorage.films.length!=0) { 
     return $localStorage.films; 
     console.log($localStorage.films); 
    }else{ 
     $http.get("json/films.json") 
     .then(function(res){ 
     console.log(res.data); 
      return res.data; 
     }); 
    } 
} 

});

此的console.log工作得很好,給我對象的數組,但在控制器:

function($scope, $mdDialog, $http, $localStorage, myStorage) { 
    $scope.films=myStorage.getFilms(); 
    console.log($scope.films); 

控制檯說未定義,任何幫助嗎?

+0

最可能的是你沒有注入依賴正常。你可以發佈整個控制器的代碼嗎? –

+0

你指的是哪一個console.log,if或者其他的呢?如果控制檯中正在打印什麼內容? – CrazyMac

+1

這可能是因爲'$ scope.films'是在解析promise之前分配的,導致未賦值的結果值。 – nocodename

回答

2

您應該返回承諾。就像這樣:

app.service('myStorage',function($http, $localStorage, $q){ 
    this.getFilms = function(){ 
    if ($localStorage.films && $localStorage.films.length!=0) { 
     return $q.when($localStorage.films); 
    } else { 
     return $http.get("json/films.json").then(function(res){ 
     console.log(res.data); 
     return res.data; 
     }); 
    } 
    } 
}); 

而且,現在的控制器,

function($scope, $mdDialog, $http, $localStorage, myStorage) { 
    myStorage.getFilms().then(function(res) { 
    $scope.films = res; 
    console.log($scope.films);   
    }) 
    ... 
}) 
+0

這是正確的,但考慮使用$ q.when,然後第一個分支只有一個一行代碼 –

+1

@AluanHaddad肯定。好點,也習慣了這一點。 :(會更新它,謝謝! – tanmay

+0

最優秀!如果我可以投票兩次... –