![](/img/trans.png)
[英]Angular2 Component inside ngFor throws Error (viewFactory is not a function)
[英]Class function inside a component while running ngFor gives Error (not a function)
我试图显示一个主题列表,其中每个列表条目都是一个自定义组件。 我将我的问题描述为我的代码的一个简单示例。
使用当前 (02/2020) 版本的 Angular、MongoDB 和 Chrome
主题类:
export class Topic {
constructor(
public title: string,
public solutionID: number[] = [],
private rating: number = 0,
private votes: number = 0
) { }
currentRating(): number {
return this.rating / this.votes;
}
vote(stars: number) {
this.votes++;
this.rating += stars;
}
lastEditDate(): Date {
console.log('test');
return this.ts_worker[this.ts_worker.length - 1];
}
}
main-view.component.html这是显示列表的“框架”
<div class="content-wrapper">
<app-topic-view *ngFor="let tp of topics" [topic]="tp"></app-topic-view>
</div>
main-view.component.ts这是我的主题的来源(从服务器获取)
import { Component, OnInit, Input } from '@angular/core';
import { TopicsService } from 'src/app/services/topics.service';
import { Topic } from 'src/app/classes/class_Topic';
@Component({
selector: 'app-main-view',
templateUrl: './main-view.component.html',
styleUrls: ['./main-view.component.scss']
})
export class MainViewComponent implements OnInit {
@Input() topics: Topic[];
constructor(private topicService: TopicsService) { }
ngOnInit() {
this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
this.topics = topics;
})
}
}
主题视图.component.html
<div class="topicElement">
<!-- Some code hidden here -->
<div class="back-group">
<div class="solutionCount">Solutions: {{(topic.ts_worker[topic.ts_worker.length - 1])}}</div>
<div class="solutionCount">Solutions: {{(topic.lastEditDate())}}</div>
</div>
</div>
在{{(topic.lastEditDate()}}
发现了错误。
上面那行工作得很好。 只有函数调用不起作用。
我在这里错过了什么
最后,我想使用我班级的功能。 我习惯用其他语言来做这件事。 这在 Angular 中可能吗?
编辑:错别字已修复
返回 http 时,您的“主题”不是类主题,因为当它传输到 javaScript 时,您只有一个对象,您需要创建为
this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
this.topics=x.map(x=>new Topic(x.title,x.solutionID,x.rating,x.votes))
})
其他人的想法是 Topic 是
export class Topic {
public title;
public solutionID;
private rating;
private votes;
constructor({ title, solutionID, rating, votes }) {
this.title = title;
this.solutionID = solutionID;
this.rating = rating;
this.votes = votes;
}
..your methods...
}
和写
this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
this.topics=x.map(x=>new Topic(x))
})
另一个想法是,在您的 app-topic-view 中,您有
private _topic:Topic
@Input() set topic(value)
{
this._topic=new Topic(value.title,value.solutionID,value.rating,value.votes)
//or if you change the constructor
// this._topic=new Topic(value);
}
get topic()
{
return this._topic;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.