【发布时间】:2015-12-30 13:07:31
【问题描述】:
我有两个 AngularJS 2.0 组件:
评论:
import {Component, Injectable, View, Input} from 'angular2/core';
import {Comments} from './comments.component';
@Injectable()
@Component({
selector: 'comment'
})
@View({
templateUrl: 'res/templates/components/comment.component.html',
directives: [Comments]
})
export class Comment {
@Input() comment;
@Input() commentable = false;
}
评论:
import {Component, Injectable, View, Input} from 'angular2/core';
import {CommentsService} from './../services/comments.service';
import {RouteParams} from 'angular2/router';
import {Comment} from './Comment.component';
@Injectable()
@Component({
selector: 'comments',
providers: [CommentsService]
})
@View({
templateUrl: 'res/templates/components/comments.component.html',
directives: [Comment]
})
export class Comments {
@Input() ID;
public comments;
public commentsService: CommentsService;
public routeParams: RouteParams;
constructor (routeParams: RouteParams, commentsService: CommentsService) {
var self = this;
self.routeParams = routeParams;
self.commentsService = commentsService;
}
ngOnInit() {
var self = this;
if (self.ID !== undefined)
self.comments = self.commentsService.comments[self.ID];
else if (self.routeParams.params['id'] !== undefined)
self.comments = self.commentsService.comments[self.routeParams.params['id']];
else
self.comments = undefined;
}
}
comment.template:
<div class="post">
<div class="author-pic"></div>
<div class="body">
<h2 class="title">{{comment.author.name}} {{comment.author.surname}}</h2>
<h3 class="title">{{comment.publication | date:"MM/dd/yy"}}</h3>
<p>{{comment.body}}</p>
</div>
<comments *ngIf="commentable" [ID]="comment.ID"></comments>
</div>
cmets.template:
<div *ngIf="comments !== undefined">
<comment *ngFor="#comment of comments" [comment]="comment" [commentable]="true"></commento>
</div>
在 Comments 的模板中,我有一个打印多个 Comment 组件的 Angular Loop。在 Comment 的模板中,我有一个 Angular ngIf,如果 var commentable 为 true,则打印一个 Comments 组件。当我运行它时,我得到:
EXCEPTION: Unexpected directive value 'undefined' on the View of component 'Comment'
【问题讨论】:
-
您能发布相关的模板和服务吗?为什么要在组件上方添加 @Injectable 装饰器?
-
很可能是因为你有一个循环依赖。评论有评论作为指令,评论也有评论作为指令。从另一个中删除其中一个。
-
如果我删除其中一个,它将无法正常工作...@Eric Martinez
-
如果现在用这种方法甚至不能正常工作,你怎么知道它不会工作?为什么需要这种循环依赖?如果你想从
Comment(父子通信)中获取Comments,可以直接注入,不需要添加为指令。 -
我发布了相关的模板@Romain。
标签: angular