ค้นหาเว็บไซต์

javascript - setInterval ใน IONIC 3


ฉันต้องการเรียกใช้ฟังก์ชันทุก ๆ 1 วินาที หลังจากค้นหา ฉันพบ setInterval แต่ก็ไม่สามารถใช้งานได้สำหรับฉัน

setInterval(function(){ 
   this.myfuntion();

}, 1000);

ฉันก็ลองใช้ this.myfuntion แต่ก็ไม่ทำงานเช่นกัน

คำตอบ #1

วิธีแก้ปัญหาคือการใช้ ฟังก์ชันลูกศร:

setInterval(() => { 
   this.myfuntion(); // Now the "this" still references the component
}, 1000);

เมื่อใช้ ฟังก์ชันลูกศร คุณสมบัติ this จะไม่ถูกเขียนทับและยังคงอ้างอิงถึงอินสแตนซ์ของคอมโพเนนต์

คำตอบ #2

โดยพื้นฐานมีสองวิธีในการทำเช่นนั้น

ลองใช้ observable ซึ่งจะเหมาะกับความต้องการของคุณที่สุด

วิธีที่ 1:

import {Observable} from 'Rxjs/rx';
import { Subscription } from "rxjs/Subscription";

// if you want your code to work everytime even though you leave the page
Observable.interval(1000).subscribe(()=>{
    this.functionYouWantToCall();
});

วิธีที่ 2:

// if you want your code to work only for this page
//define this before constructor
observableVar: Subscription;

this.observableVar = Observable.interval(1000).subscribe(()=>{
    this.functionYouWantToCall();
});

ionViewDidLeave(){
   this.observableVar.unsubscribe();
}

บทความที่เกี่ยวข้อง