执行Angular函数一次并在重新加载组件后保留它。

huangapple go评论73阅读模式
英文:

How to execute angular function one time and leave it also after reload component

问题

我正在学习Angular并面临以下问题 - 如果我理解正确 - 我在ngOnInit中放入的所有内容都会在每次组件重新加载时执行。我有一个定时器函数,需要在页面重新加载时继续运行,而不是重新开始计数。我如何在ngOnInit之外或HTML中执行startTimer(secsToStart: number)函数,或者是否有其他Angular功能我需要查看。

组件代码:

@Component({
  selector: 'app-task-countdown',
  templateUrl: './task-countdown.component.html',
  styleUrls: ['./task-countdown.component.css'],
})
export class TaskCountdownComponent implements OnInit {
  @Input()
  tasks!: Tasks[];
  excuse!: Loosers[];
  excuseForm!: FormGroup;
  expirationCounter!: string;
  timeIsUp = false;
  donePushed = false;

  constructor(
    private fb: FormBuilder,
    private tasksService: TasksService,
    private excuseService: ExcuseService,
    private router: Router
  ) {}

  ngOnInit() {
    this.tasks = this.tasksService.getTasks();
    this.startTimer(86400);
    this.excuseForm = this.fb.group({
      excuse: '',
    });
    
    this.excuseForm.valueChanges.subscribe(console.log);
  }

  addExcuse() {
    const excuseValue = this.excuseForm.value;
    this.excuseService.addExcuse(excuseValue);
    this.router.navigate(['/loosers']);
  }

  onTaskDone() {
    this.donePushed = true;
  }

  startTimer(secsToStart: number): void {
    // ... (定时器函数的代码)
  }
}

HTML部分,计时器在span中执行,显示在expirationCounter

<app-nav-bar></app-nav-bar>

<div *ngFor="let tasks of tasks">
  <p>{{ tasks.task }}</p>
  <button (click)="onTaskDone()">Done</button>
</div>

<div>
  <span id="myTimeCounter">{{ expirationCounter }}</span>
</div>
<div *ngIf="this.timeIsUp">
  <form [formGroup]="excuseForm">
    <input
      type="text"
      placeholder="写下你的借口..."
      formControlName="excuse"
    />
    <button (click)="addExcuse()">Add</button>
  </form>
</div>

如果你想在组件加载后仍然保持定时器运行,可以将startTimer函数的调用移到constructor中,这样它将在组件初始化时执行而不会在每次重新加载时重新开始计数。

英文:

Im learning angular and facing following question - if i understand right - all what i put in ngOnInit, is executed on each component reload. I have timer function, which needs to keep running also if page is reloaded, not start new count. How can i execute function startTimer(secsToStart: number) outside ngOnInit, or in HTML, or there is other angular feature i need to look into.

The component code:

@Component({
  selector: &#39;app-task-countdown&#39;,
  templateUrl: &#39;./task-countdown.component.html&#39;,
  styleUrls: [&#39;./task-countdown.component.css&#39;],
})
export class TaskCountdownComponent implements OnInit {
  @Input()
  tasks!: Tasks[];
  excuse!: Loosers[];
  excuseForm!: FormGroup;
  expirationCounter!: string;
  timeIsUp = false;
  donePushed = false;


  constructor(
    private fb: FormBuilder,
    private tasksService: TasksService,
    private excuseService: ExcuseService,
    private router: Router
  ) {}

  ngOnInit() {
    this.tasks = this.tasksService.getTasks();
    this.startTimer(86400);
    this.excuseForm = this.fb.group({
      excuse: &#39;&#39;,
    });
    
    this.excuseForm.valueChanges.subscribe(console.log);
  }

  addExcuse() {
    const excuseValue = this.excuseForm.value;
    this.excuseService.addExcuse(excuseValue);
    this.router.navigate([&#39;/loosers&#39;]);
  }

  onTaskDone() {
    this.donePushed = true;
  }


  startTimer(secsToStart: number): void {
    var start: number = secsToStart;
    var h: number;
    var m: number;
    var s: number;
    var temp: number;
    var timer: any = setInterval(() =&gt; {
      h = Math.floor(start / 60 / 60);
      temp = start - h * 60 * 60;
      m = Math.floor(temp / 60);
      temp = temp - m * 60;
    
      s = temp;

      var hour = h &lt; 10 ? &#39;0&#39; + h : h;
      var minute = m &lt; 10 ? &#39;0&#39; + m : m;
      var second = s &lt; 10 ? &#39;0&#39; + s : s;

      this.expirationCounter = hour + &#39;:&#39; + minute + &#39;:&#39; + second;

      if (start &lt;= 0) {
        clearInterval(timer);
        this.expirationCounter = &#39;Expired&#39;;
        this.timeIsUp = true;
        this.tasks = [];
      } else if (this.donePushed) {
        clearInterval(timer);
        console.log(start);
      }
      start--;
    }, 1000);
  }
}

The html part, the timer is executed in span as expirationCounter:

&lt;app-nav-bar&gt;&lt;/app-nav-bar&gt;

&lt;div *ngFor=&quot;let tasks of tasks&quot;&gt;
  &lt;p&gt;{{ tasks.task }}&lt;/p&gt;
  &lt;button (click)=&quot;onTaskDone()&quot;&gt;Done&lt;/button&gt;
&lt;/div&gt;

&lt;div&gt;
  &lt;span id=&quot;myTimeCounter&quot;&gt;{{ expirationCounter }}&lt;/span&gt;
&lt;/div&gt;
&lt;div *ngIf=&quot;this.timeIsUp&quot;&gt;
  &lt;form [formGroup]=&quot;excuseForm&quot;&gt;
    &lt;input
      type=&quot;text&quot;
      placeholder=&quot;write down your excuses .. &quot;
      formControlName=&quot;excuse&quot;
    /&gt;
    &lt;button (click)=&quot;addExcuse()&quot;&gt;Add&lt;/button&gt;
  &lt;/form&gt;
&lt;/div&gt;

答案1

得分: 2

当重新加载页面时,Angular 会失去所有已收集的信息(例如当前计数状态)。

您应该考虑在每次计数时将当前计数保存在本地存储中,然后在页面/组件加载时从那里加载它。

// 写入
let mycount: number = 5;
localStorage.setItem("countvalue", String(5));

// 读取
let mycount: string = localStorage.getItem("countvalue");
英文:

When you reload the page angular losses all informations hat has been gathered (like the current count state).

You should consider saving the current count in localstorage on each count and load it from there when the page/components load.

// write
let mycount: number = 5;
localStorage.setItem(&quot;countvalue&quot;, String(&quot;5&quot;));

// read
let mycount: string = localStorage.setItem(&quot;countvalue&quot;);

huangapple
  • 本文由 发表于 2023年2月23日 19:56:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定