So I'm making a service in angular but when I call it in my controller it doesn't work... Here is the service :
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;
};
});
And in my controller I try to call it like that:
app.controller('PostsCtrl', function($scope, AllPosts){
$scope.posts = AllPosts.getPosts;
});
When I try to use the function .getPosts I have an empty white page but if I replace .getPosts by .posts I have my page loading right...
$scope.posts = AllPosts.posts;
What am I doing wrong guys, please?
In your code you are assigning $scope.posts
to a function:
$scope.posts = AllPosts.getPosts;
You should call the function so that the result of the method call is assigned to $scope.posts
:
$scope.posts = AllPosts.getPosts();
Now, $scope.posts
will be assigned to the posts that are returned by the method.
I edited the code to work as a function or as a variable.
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;
});
};
});
In your controller: as @Amin Meyghani and @ Mike C mentioned:
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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.