提供Json AngularJS的服务

时间:2017-04-25 12:45:35

标签: javascript angularjs angular-services

嗨,我有这个服务的问题

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);

控制台说未定义,有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

你应该返回一个承诺。像这样:

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

而且,现在在控制器中,

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-color: lightblue;
}

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    }
}
@media screen and (max-width: 300px) {
.cert{ display:none; }
}
}
</style>
</head>
<body>
<div class="cert">
    <h1 class="certname">
        <?php
        global $current_user;
        get_currentuserinfo();
        echo 'Hi, <a href="https://vle.uxbridge.ac.uk/intranet/members/' . $current_user->user_login . '/profile/change-avatar/">' . $current_user->display_name . '</a>' . "\n";

        ?></h1>
    <h2 class="certemail">
        <?php
        global $current_user;
        get_currentuserinfo();
        echo '<a href="https://outlook.office.com/owa/" target="_blank">' . $current_user->user_email . '</a>' . "\n";

        ?>
    </h2>
</div>

</body>
</html>