Функция класса внутри компонента при запуске ngFor выдает ошибку (не функция) - PullRequest
2 голосов
/ 19 февраля 2020

Я пытаюсь показать список тем , где каждая запись в списке является пользовательским компонентом. Я опишу свою проблему в качестве простого примера моего кода.

Использование текущей (02/2020) версии Angular, MongoDB и Chrome

Topi c класс:

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;
    })
  }

}

topi c -view. компонент. 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()}}.

Строка выше, которая работает просто отлично. Не работает только вызов функции.

Ошибка Image of Error

Цель How it looks renderes


Что мне здесь не хватает

В конце я бы хотел использовать функции моего класса. Я привык делать это на других языках. Это возможно в Angular?

РЕДАКТИРОВАТЬ: опечатка исправлена ​​

1 Ответ

2 голосов
/ 19 февраля 2020

ваши "темы" не относятся к классу Topi c при возврате http, потому что, когда он простирается до javaScript, у вас есть только объект, вам нужно создать как

 this.topicService.getAllTopics().subscribe((topics: Topic[]) => {
      this.topics=x.map(x=>new Topic(x.title,x.solutionID,x.rating,x.votes))
    })

Другая идея заключается в том, что что Topi c был

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))
    })

И еще одна идея заключается в том, что в вашем приложении topi c -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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...