1

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.
  }

}
2
  • What's the actual error? What's even the question? Commented Sep 24, 2017 at 18:35
  • @Lazar, as I mentioned above, it is producing error in returning promise . Commented Sep 24, 2017 at 18:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but the same piece of code that i mentioned above run without any error on a tutorial, can't figure why it produced error in my case.
Editing my answer to shed more light.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.