2016-11-29 2 views
-2

Теперь свойства {{article.}} Все работают нормально и отображают, что они на веб-странице, почему article.comments (внизу html) говорит, что статья не определена когда он вводит страницы? Благодарю.angular 2 Невозможно прочитать комментарии к свойствам undefined

Aricle.cs модель импорт {комментарий} из './comment';

export class Article { 
    id : number; 
    isanon : boolean; 
    title: string; 
    link: string; 
    text: string; 
    subverse : string; 
    userID : string; 
    votes: number; 
    comments : Comment[]; 

    constructor(title: string, link: string, subverse : string, text : string, userID : string, votes?: number) { 
    this.title = title; 
    this.link = link; 
    this.text = text; 
    this.subverse = subverse; 
    this.userID = userID; 
    this.votes = votes || 0; 
    this.comments = new Array<Comment>(); 
    } 

    log() : void{ 
    console.log("Title: " + this.title + " Link: " + this.link + " subverse: " + this.subverse); 
    } 

    domain(): string { 
    try { 
     return this.link; 
    } catch (err) { 
     return null; 
    } 
    } 

    voteUp(): void { 
    this.votes += 1; 
    } 

    voteDown(): void { 
    this.votes -= 1; 
    } 


} 

articlefullpage.component.html

<div class="ui large segment"> 
<div class="field"> 
    Article Title: {{article.title}} 
</div> 
<div class="field"> 
    Article Link: <a href="{{article.link}}">{{article.link}}</a> 
</div> 
<div class="field"> 
    User Text: {{article.text}} 
</div> 
<div class="field"> 
    Subverse: {{article.subverse}} 
</div> 
<div class="field"> 
    Votes: {{article.votes}} 
</div> 
</div> 
<br/><br/> 

<div class="ui large segment"> 
Add comment 
<form class="form ui large segment"> 
<textarea rows="10" cols="10" #comment> 

</textarea> 
    <!-- added this button --> 
    <button (click)="addComment(comment)" 
      class="ui positive right floated button"> 
    Submit link 
    </button> 
</form> 
</div> 

<app-comment-tree [commentTree]="article.comments"></app-comment-tree> 

articlefullpage.component.ts

import { 
    Component, 
    OnInit, 
    Input 
} from '@angular/core'; 
import { Article } from '../models/article'; 
import {Location} from '@angular/common'; 
import {AppServiceHackersPulse} from '../services/app.service.hackerspulse'; 
import {User} from '../models/user'; 
import {Comment} from '../models/comment'; 

@Component({ 
    selector: 'app-articlefullpage', 
    templateUrl: './app/articlefullpage/articlefullpage.component.html', 
    styleUrls: ['./app/articlefullpage/articlefullpage.component.css'], 
    host: { 
    class: 'row' 
    }, 
    providers: [AppServiceHackersPulse] 
}) 
export class ArticleFullPageComponent implements OnInit { 
    @Input() article : Article; 
    service : AppServiceHackersPulse; 
    user : User; 
    Id : string; 

    constructor(private location : Location, private hpService: AppServiceHackersPulse) 
    { 
    this.service = hpService; 
    this.Id = location.path().split('/')[2]; 

    this.service.GetUser().subscribe((data) => { 
     this.user = data; 
    }); 
    } 

    ngOnInit() { 


    } 

    getArticle() : Article 
    { 
    return this.article; 
    } 

    addComment(comment : HTMLInputElement) 
    { 
    var c : Comment = new Comment(0,0,this.user.id,comment.value,Number(this.Id)); 
    this.article.comments.push(c); 
    console.log("comment: " + comment.value); 
    } 

} 

Полная ошибка

core.umd.js:2837EXCEPTION: Uncaught (in promise): Error: Error in app/articlefullpage/articlefullpage.component.html:33:18 caused by: Cannot read property 'comments' of undefined 
TypeError: Cannot read property 'comments' of undefined 
    at CompiledTemplate. 
+0

Полный источник: https://github.com/claysmith/hackerspulse –

ответ

1

Первый порт вызова положить * ngIf на оскорбительный тег:

<app-comment-tree *ngIf="article" [commentTree]="article.comments"></app-comment-tree> 

Представление может пытаться получить доступ к свойству статьи до его инициализации.

+0

Да, это он. Есть что-то вроде ngIf для всей страницы? Или мне нужно помешать вещам, которые используют статьи с * ngIf = "article" –

+1

Вы могли бы также написать статью? .comments, которая проверяет, определены ли статьи, и только потом приступает к финансированию комментариев. – lastWhisper

0

Где моя компонента app-comment-tree? Проблема заключается в том, что article не определен в этом настраиваемом компоненте. Вам необходимо импортировать класс из этого компонента и получить к нему доступ как ArticleFullPageComponent.article.comments в шаблоне articlefullpage.component.html, если он определен как общедоступное.

Или вы можете определить его в том настраиваемом компоненте, который вы не разместили.

Надеюсь, это поможет.

Смежные вопросы