How to use IonViewCanEnter with an observable?


#1

I’m trying to use IonViewCanEnter as a guard for one of my app’s pages. The problem is I can’t figure out how to get ionViewCanEnter to wait for a value from an observable. With subscribe I can get the value and print to console, but by then it’s too late and is returning a subscription.

I assumed some similarity to Angular 2’s CanActivate in that I need to return a completed Observable, but solutions that I’ve found that use map with .take(1) or first() don’t seem to fire at all.

From my page:

ionViewCanEnter() {
  return this._auth.checkToken()
    .map(
      res => {
        console.log(res);
        return false;
      },
      err => {
        console.log(err);
      }
    )
    .take(1)
    // .subscribe(
    //   res => {
    //     console.log(res);
    //     return res;
    //   },
    //   err => {
    //     console.error(err);
    //   }
    // );
  }

From my _auth provider:

checkToken() {
    return Observable
      .fromPromise(this.defaultOptions())
      .switchMap(
        options => {
          return this.http.get(Config.API_ENDPOINT + '/api/', options)
            .map(res => res.json())
            .map(
              res => {
                if (res.auth_token) {
                  this.setToken(res.auth_token, undefined);
                  return true;
                }
                // this.logout();
                return false;

              },
              err => {
                return false;
                // this.logout();
              }
            )

        }
      );
  }

#2

Hi,

Did you find any solution to this problem with Ionic2?
I am stuck in the same situation and any help would be appreciated!

Thanks!


#3

Hi,

Was wondering how to use it with a Promise and I came across this thread. The ionViewCanEnter appears to accept either a boolean or Promise<boolean>.
You should be able to use the .toPromise() method on the observable as the return value.


#4

Hi,

Thank you so much for your response on this.
I changed my service to return promise now (with toPromise()), and ionViewCanEnter to return Promise < boolean > .
This works as charm !!

Thanks again!!


#5

In Ionic 3 I was able to use BehaviorSubject.value to synchronously return the value to ionViewCanEnter


#6

My solution is to use a BehaviorSubject<boolean> as the Observable, then use first().toPromise() to get the last value as a Promise.

code snip:

const sub = new BehaviorSubject<boolean>(false)
const valid = sub.asObservable().distinctUntilChanged()

// ...

function validPromise() {
  return valid.first().toPromise()
}

Hope this helps.