0

I'm trying to figure out how to return an observable to from the canActivate method in my guard, but I can't seem to figure it out.

I've read a bunch of answers regarding this, especially this one Angular2 - return boolean with subscribe to canActivate. I followed this answer pretty closely, but it still isn't working.

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

        return this._adminService.maintenanceOptions('maint-options').map(data => {
            if (data['maintSwitch'] == 'off') {
                const navigationExtras: NavigationExtras = {
                    queryParams: { errorMessage: data['maintComment'] }
                };
                this.router.navigate(['/maintenance'], navigationExtras);
                return false;
            }
            return true;
        });
   }
  maintenanceOptions(apiPath: string) {
    this.toggleLoading(true);

    const url = this._baseUrl + apiPath;
    const options = this._authService.getOptions();

    return this.http.get(url, options)
      .take(1)
      .map((res: Response) => res.json())
      .finally(() => this.toggleLoading(false));
  }

I expected this to be able to accept the observable, but I'm making an error somewhere here. I keep getting this error in the chrome console:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of null
TypeError: Cannot read property 'length' of null at
HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate

and then the error continues on and on.

zmag
  • 7,825
  • 12
  • 32
  • 42
csStudent
  • 128
  • 2
  • 12
  • FYI angulars HttpClient handles the json object for you when you are calling a server so no need to do ```res.json()``` – Patricio Vargas Jun 04 '19 at 23:46
  • 1
    Have you set any break points to indicate whether it breaks inside `maintenanceOptions` or in the mapper of `canActivate`? To me, it looks like the options within the http request is breaking the app. Also, it would be best practice to use `pipe` strategy for rxjs operators. If you are using angular 7.1+ you can return UrlTree object rather than `this.router.navigate` – Ngoc Nam Nguyen Jun 04 '19 at 23:54
  • You're right, it was in the options in the http request. I was sending an undefined variable – csStudent Jun 05 '19 at 15:37

0 Answers0