递归调用 Angular 工厂会产生循环依赖错误
Calling an Angular Factory recursively gives a circular dependency error
我有一个带有多线程评论的应用程序,我正在尝试使用 Angular 工厂递归地创建具有所有必要功能和属性的对象,因为当然,一条评论可以有很多回复,每一个都可以有更多的回复...
下面是我厂代表的评论:
app.factory("Comment", ["commentHttpService", "Comment", function(commentHttpService, Comment) {
return function(comment) {
var self = comment;
// lots of other properties and methods here
self.children = self.children.map(function(reply) {
return new Comment(reply);
});
return self;
}
}]);
当然,这不起作用,因为我正在将 Comment
注入自身。
我怎样才能解决这个问题并仍然完成我最初的目标?
app.factory("Comment", ["commentHttpService", function(commentHttpService) {
function Comment(comment) {
var self = comment;
// lots of other properties and methods here
self.children = self.children.map(function(reply) {
return new Comment(reply);
});
}
return Comment;
}]);
另一种实现你想要的方法是创建一个工厂,让你创建一个 Comment 实例,它附加了它的所有 api:
app.factory("CommentFactory", function() {
function Comment(comment) {
this.message = comment;
this.replies = [];
this.getMessage = function() {
return this.message;
}
this.addReply = function(reply) {
var replyComment = new Comment(reply);
this.replies.push(replyComment);
return replyComment;
}
this.getReplies = function() {
return replies;
}
}
return {
createComment: function(message) {
return new Comment(message);
}
}
});
这是一个小插曲:
http://plnkr.co/edit/BmfCm9?p=preview
您可以使用工厂创建评论并添加对评论的回复,这些评论也是 Comments 的实例。
我有一个带有多线程评论的应用程序,我正在尝试使用 Angular 工厂递归地创建具有所有必要功能和属性的对象,因为当然,一条评论可以有很多回复,每一个都可以有更多的回复...
下面是我厂代表的评论:
app.factory("Comment", ["commentHttpService", "Comment", function(commentHttpService, Comment) {
return function(comment) {
var self = comment;
// lots of other properties and methods here
self.children = self.children.map(function(reply) {
return new Comment(reply);
});
return self;
}
}]);
当然,这不起作用,因为我正在将 Comment
注入自身。
我怎样才能解决这个问题并仍然完成我最初的目标?
app.factory("Comment", ["commentHttpService", function(commentHttpService) {
function Comment(comment) {
var self = comment;
// lots of other properties and methods here
self.children = self.children.map(function(reply) {
return new Comment(reply);
});
}
return Comment;
}]);
另一种实现你想要的方法是创建一个工厂,让你创建一个 Comment 实例,它附加了它的所有 api:
app.factory("CommentFactory", function() {
function Comment(comment) {
this.message = comment;
this.replies = [];
this.getMessage = function() {
return this.message;
}
this.addReply = function(reply) {
var replyComment = new Comment(reply);
this.replies.push(replyComment);
return replyComment;
}
this.getReplies = function() {
return replies;
}
}
return {
createComment: function(message) {
return new Comment(message);
}
}
});
这是一个小插曲: http://plnkr.co/edit/BmfCm9?p=preview
您可以使用工厂创建评论并添加对评论的回复,这些评论也是 Comments 的实例。