Reputation: 73
Here, I am getting error in following code below indicated as I want to return promise but getting error in returning promise. How to returning promise?
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { UsersPage } from '../users/users';
import { ShopPage } from '../shop/shop';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
usrPage = UsersPage;
constructor(public navCtrl: NavController) {}
onGoToUsers(){
this.navCtrl.push(this.usrPage)
.catch((error)=> console.log('Access Denied, Argument was' + error));
}
ionViewCanLeave(): boolean | Promise<void> {
const promise = new Promise((resolve, reject) => {
setTimeout(()=>{
resolve()
}, 1000);
});
return promise; // the line is producing error in returning promise.
}
}
Upvotes: 1
Views: 52
Reputation: 1004
Change ionViewCanLeave(): boolean | Promise<void> {
to this.
ionViewCanLeave(): boolean | Promise<any> {
Essentially, Promise<void>
is not equal to Promise
in your case. (which you return). Thus change the <T>
of the promise to use any
as the generic value.
The reason void
is not equal to any
is that void
essentially means an absence of a type whereas any
means any type. undefined
and null
can be assigned to a void
type variable.
The line const promise = new Promise...
declares the variable type implicitly as you do not give the type after the promise
declaration, so it assumes it to be Promise<any>
.
Thus, if you would write const promise: Promise<void>
and it would also work.
Another way this could work would be to return the Promise
directly like this: (Perhaps the tutorial you followed showed the function like this?)
return new Promise((resolve, reject) => {
//
});
Since this is a return statement it would tell the typescript compiler to implicitly assume the correct return type that is Promise<void>
instead of Promise<any>
since that happens when you assign this Promise to a typeless const promise
.
Hope I was able to shed some light. Read more about typescript types from here.
Upvotes: 2