"ИСКЛЮЧЕНИЕ: Неожиданное значение директивы 'undefined' в представлении компонента" во вложенных компонентах
У меня есть два компонента 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;
}
}
комментарий .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>
comments.template:
<div *ngIf="comments !== undefined">
<comment *ngFor="#comment of comments" [comment]="comment" [commentable]="true"></commento>
</div>
В шаблоне комментариев у меня есть контур Angular, который печатает несколько компонентов Comment. В шаблоне комментариев у меня есть Angular ngIf, что, если var commentable is true, печатает компонент Comments. Когда я запускаю его, я получаю:
EXCEPTION: Unexpected directive value 'undefined' on the View of component 'Comment'
Ответы
Ответ 1
Существует способ решить проблему с круговой зависимостью.
import {forwardRef} from 'angular2/core';
import {Comment} from './Comment.component';
...
directives: [forwardRef(() => Comment)]
})
Я пробовал это с помощью 2.0.0-beta.10
, и он отлично работает. Для получения дополнительной информации см. Комментарий tlancina в этом выпуске для github.
Ответ 2
Круговая зависимость TypeScript может вызвать это. (Я просто столкнулся с этим)
Для меня:
-
A - это родительский компонент и import
и export
B, C, D. для удобства.
-
A пытается отобразить B
-
B импортирует C из A и пытается отобразить C.
Как только я добавлю C в блок directives
B, я получаю эту ошибку (будь то в шаблоне B или нет.) Действительно, поскольку A зависит от B, в тот момент, когда я импортирую что-либо из A в блок B Я получаю
Неожиданное значение директивы 'undefined'
@Eirc Martinez прав, и вам нужно будет найти путь вокруг этой круговой зависимости.
Ответ 3
Я часто получаю эту ошибку, когда я импортировал что-то, что не существует. Обычно это означает наличие орфографической ошибки в моем импорте или что-то такое же.
Например, я получаю эту ошибку при попытке импортировать:
import {Comment} from './Comment.component';
Когда я на самом деле имею в виду:
import {CommentComponent} from './Comment.component';
Ответ 4
У меня проблема такая. Хотя это проблема, чувствительная к регистру. Наконец, решите это.
courses.component.ts
import {Component} from 'angular2/core'
@Component({
selector: 'courses',
template: '<h2>Courses</h2>'
})
export class coursesComponent{
}
Ошибка - курсыCompomnent класс должен быть CoursesCompomnent. Просто C - заглавная буква.
app.component.ts
import { Component } from 'angular2/core';
import{CoursesComponent} from './courses.component';
@Component({
selector: 'my-app',
template: '<h1>Hello Angular</h1><courses></courses>',
directives: [CoursesComponent]
})
export class AppComponent {
}
https://github.com/angular/angular/issues/7526