繁体   English   中英

AngularJS:服务中的函数不起作用

[英]AngularJS : Functions in Service doesn't work

所以我正在以角度进行服务但是当我在我的控制器中调用它时它不起作用......这是服务:

app.service('AllPosts', function(){
    this.posts = [
        {"id":"0","username":"Simon", "age":"18"},
        {"id":"1","username":"Chris", "age":"53"}
    ];
    this.getPosts = function(){
        return this.posts;
    };
    this.getPost = function(id){
        var post={};
        angular.forEach(this.posts, function(value) {
            if(value.id == id){
                post=value;
            }
        });
        return post;
    };
});

在我的控制器中,我试着这样称呼它:

app.controller('PostsCtrl', function($scope, AllPosts){
    $scope.posts = AllPosts.getPosts;
});

当我尝试使用函数.getPosts时,我有一个空的白页但是如果我用.posts替换.getPosts我的页面加载正确...

$scope.posts = AllPosts.posts;

我做错了什么,拜托?

在您的代码中,您将$scope.posts分配给函数:

$scope.posts = AllPosts.getPosts;

您应该调用该函数,以便将方法调用的结果分配给$scope.posts

$scope.posts = AllPosts.getPosts();

现在, $scope.posts将分配给该方法返回的帖子。

我编辑了代码以作为函数或变量工作。

app.service('AllPosts', function(){
    var posts = [
        {"id":"0","username":"Simon", "age":"18"},
        {"id":"1","username":"Chris", "age":"53"}
    ];
    this.getPosts = function(){
        return this.posts;
    };
    // or you can do this by calling it.
    this.getPosts = this.posts;
    // Using functional programming and arrow function.
    this.getPost = function(id){
         return this.posts.filter((value) => {
           return value.id == id;
       });
    };
});

在你的控制器中: @Amin Meyghani和@ Mike C提到:

app.controller('PostsCtrl', function($scope, AllPosts){
    // You need to comment one of these
    // to use it as a function.
    $scope.posts = AllPosts.getPosts();
    // or if you want to use it as avarible .
    $scope.posts = AllPosts.getPosts
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM