Reputation: 1180
I am working on ionic 4 and angular. My app is content on flights schedule. What l am trying to do is to receive local notification from my server if specific flight is arrive. l use setInterval
for reloading server to check if flights is arrive or not. The problem is when the flights are arrived the setInterval
still reloading, also I used clearInterval
but doesn't stop.
async ActiveNotif() {
this.ng.run(() => {
// reloading
this.interval= setInterval(()=>{
this.http.get('flight=' + this.id + '', {}, {})
.then(data => {
let FlightDetails = JSON.parse(data.data);
this.identification = FlightDetails.identification.callsign;
this.Fstatus = FlightDetails.status.generic.status.text;
console.log(this.Fstatus)
});
//checking
if (this.Fstatus == "landed") {
this.localNotifications.schedule(
[
{
id:0,
title: 'Your flight has arrived',
text: 'Your flight ' + this.identification + 'is arrived',
trigger: { count: 1 },
sound: "file://assets/one.mp3"
},
]);
}
},10000)
if (this.Fstatus == "landed") {
clearInterval(this.interval)
}
})
}
Upvotes: 0
Views: 76
Reputation: 57919
http.get is an observable, not a promise. You need subscribe, not use "then". If you use httpClient, it's not necesary "parser", the data becomes as json yet
BTW I like much more the 'rxjs' timer, and use takeWhile to stopped, and switchMap to get the response
this.dataReaded=false;
timer(0,1000).pipe(
takewhile(()=>!this.dataReaded),
switchMap(()=>{
return this.httpClient.get('flight=' + this.id + '', {}, {})
}))
.subscribe(res=>{
const FlightDetails = data.data;
this.identification = FlightDetails.identification.callsign;
this.Fstatus = FlightDetails.status.generic.status.text;
this.dataReaded=true;
})
Upvotes: 0
Reputation: 7949
Try out this solution . Try to make set interval
and clear interval
as i do .
Check out the solution .
async ActiveNotif() {
this.ng.run(() => {
// reloading
var time = setInterval(callingFunction , 10000);
function callingFunction(){
this.http.get('flight=' + this.id + '', {}, {})
.then(data => {
let FlightDetails = JSON.parse(data.data);
this.identification = FlightDetails.identification.callsign;
this.Fstatus = FlightDetails.status.generic.status.text;
console.log(this.Fstatus)
});
if (this.Fstatus == "landed") {
this.localNotifications.schedule(
[
{
id:0,
title: 'Your flight has arrived',
text: 'Your flight ' + this.identification + 'is arrived',
trigger: { count: 1 },
sound: "file://assets/one.mp3"
},
]);
}
if (this.Fstatus == "landed") {
clearInterval(time)
}
}
})
}
Upvotes: 0
Reputation: 2018
The clearInterval
clause should be inside your interval
so that the if
is called periodically with the get
result :)
Upvotes: 1