Реализация функции отсутствует или не сразу после объявления. в angular проблема с тс - PullRequest
0 голосов
/ 12 февраля 2020

, пожалуйста, помогите мне с таймером обратного отсчета.

ошибка, которую я сейчас получаю, заключается в следующем: реализация функции отсутствует или не сразу после объявления.

это из приложения .component. html

<div app-landing>

</div>

это html код

<div class="container">

    <!-- LEFT SIDE -->


    <div class="split left" id="upComing">
        <h1 id="uce">THE UPCOMING EVENT</h1>
        <table id="tableTimer">
            <tr id="timerValue">
                <td id="days"></td>
                <td id="hrs"></td>
                <td id="mins"></td>
                <td id="secs"></td>

            </tr>
            <tr id="timerSub">
                <td>Days</td>
                <td>Hours</td>
                <td>Minutes</td>
                <td>Seconds</td>

            </tr>
        </table>
    </div>


    <!-- RIGHT SIDE -->


    <div class="split right" id="nextFive">
        <h1 id="nfe">THE NEXT FIVE EVENTS</h1>
        <table>

        </table>
    </div>
</div>


<div class="footer" id="footer"></div>

это файл ts. Я совершенно новичок в angular и TS, помогите мне решить проблему с отображением таймера обратного отсчета в стороне таблицы. и не могу сделать.


    enter code hereimport { Component, OnInit } from '@angular/core';

@Component({
  selector: '[app-landing]',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  countDown() {
    var today, eventDay, currentTime, eventTime, remainTime, sec, min, hr, days;

    today = new Date();
    eventDay = new Date();

    currentTime = today.getTime();
    eventTime = eventDay.getTime();

    remainTime = eventTime - currentTime;
    sec = Math.floor(remainTime / 1000);
    min = Math.floor(sec / 60);
    hr = Math.floor(min / 60);
    days = Math.floor(hr / 24);

    hr %= 24;
    min %= 60;
    sec %= 60;

    hr = (hr < 10) ? '0' + hr : hr;
    min = (min < 10) ? '0' + min : min;
    sec = (sec < 10) ? '0' + sec : sec;

    document.getElementById('days').innerText = days;
    document.getElementById('days').textContent = days + '' + ':';
    document.getElementById('hrs').textContent = hr + '' + ':';
    document.getElementById('mins').textContent = min + '' + ':';
    document.getElementById('secs').textContent = sec;

    setInterval(this.countDown, 1000);


}

countDown();

Ответы [ 2 ]

1 голос
/ 12 февраля 2020
  1. Вы звоните countdown() в теле класса компонента. Это не действительно javascript. Вы должны вызывать this.countdown(); из ngOnInit ().
ngOnInit(): void {
  this.countdown();
}

ngOnInit является частью Angular framework и запускаться Angular при загрузке компонента, если он существует.

Вы вручную управляете DOM. Это не "Angular путь". Вместо этого вы обновляете модель (свойства компонента) и связываетесь с моделью в HTML, чтобы обновить DOM.

html


<!-- instead of -->
<td id="days"></td>

<!-- bind read-only values using interpolation -->
<td>{{days}}</td>

ts

days: number;

countdown(): void {
    const today = new Date();
    const eventDay = new Date();

    const currentTime = today.getTime();
    const eventTime = eventDay.getTime();

    const remainTime = eventTime - currentTime;

    let sec = Math.floor(remainTime / 1000);
    let min = Math.floor(sec / 60);
    let hr = Math.floor(min / 60);
    let days = Math.floor(hr / 24);

    hr %= 24;
    min %= 60;
    sec %= 60;

    hr = (hr < 10) ? '0' + hr : hr;
    min = (min < 10) ? '0' + min : min;
    sec = (sec < 10) ? '0' + sec : sec;

    this.days = days;

    // TODO: add and set the other properties

    setInterval(() => this.countDown(), 1000);
}

РЕДАКТИРОВАТЬ

Вы должны следовать официальному учебнику Angular: https://angular.io/tutorial. Это отличная отправная точка.

0 голосов
/ 12 февраля 2020

просто измените свой код следующим образом

ts файл

  ngOnInit(){
   this.countDown();
  }
  timer={days:'',hr:'',min:'',sec:''}


   countDown() {
    var today, eventDay, currentTime, eventTime, remainTime, sec, min, hr, days;
    window.setInterval(()=>{
    today = new Date();
    eventDay = new Date('2020-02-14');
    currentTime = today.getTime();
    eventTime = eventDay.getTime();

    remainTime = eventTime - currentTime;
    sec = Math.floor(remainTime / 1000);
    min = Math.floor(sec / 60);
    hr = Math.floor(min / 60);
    days = Math.floor(hr / 24);
    hr %= 24;
    min %= 60;
    sec %= 60;
   this.timer={sec,days,min,hr}

 }

в вашем html как этот

<div class="container">

<!-- LEFT SIDE -->


<div class="split left" id="upComing">
    <h1 id="uce">THE UPCOMING EVENT</h1>
    <table id="tableTimer">
        <tr id="timerValue">
            <td id="days">{{timer.days}}</td>
            <td id="hrs">{{timer.hr}}</td>
            <td id="mins">{{timer.min}}</td>
            <td id="secs">{{timer.sec}}</td>

        </tr>
        <tr id="timerSub">
            <td>Days</td>
            <td>Hours</td>
            <td>Minutes</td>
            <td>Seconds</td>

        </tr>
    </table>
</div>


<!-- RIGHT SIDE -->


<div class="split right" id="nextFive">
    <h1 id="nfe">THE NEXT FIVE EVENTS</h1>
    <table>

    </table>
</div>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...