1
votes

Using Angular with AngularFire2 (Firebase package) and am trying to use a guard to prevent all users except one from accessing a specific route. But the code below won't work. I get the error:

Class 'AuthGuard' incorrectly implements interface 'CanActivate'. Type 'void' is not assignable to type 'boolean | Observable | Promise'.

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { AngularFire, FirebaseListObservable } from 'angularfire2';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private af: AngularFire) { }

  canActivate() {
    this.af.auth.subscribe(auth => {
      if (auth.uid === 'xyz123') {
        return Observable.of(true);
      } else {
        return Observable.of(false);
      }
    })
  }
}
1
You can also just return true and false (without an Observable)Günter Zöchbauer
Not inside a subscribeWeblurk
Ah, I missed that line. You shouldn't use subscribe at allGünter Zöchbauer

1 Answers

2
votes
  canActivate() {
    return this.af.auth
    .map(auth => {
      return auth.uid === 'xyz123';
    })
  }

The router expects a boolean or Observable<boolean> but if you call subscribe canActivate will return a Subscription. If you use map the return value will be an Observable.