在使用ActivationGuard连接来自身份验证服务的asynchro请求时遇到了困难

时间:2017-04-28 12:47:10

标签: javascript angular authentication asynchronous rxjs

我正在努力将ActivationGuardUserAuthenticationService联系起来,如果给定的用户是否已登录,则会从服务器返回。这里的主要问题是事实,它来自异步请求。

我已经获得了一些代码,这些代码是在Stack上的一个用户的帮助下完成的。它是用可观察的东西制作的。

但问题是我在输入受保护的组件时遇到以下错误:

zone.js:388 Unhandled Promise rejection: Cannot read property 'do' of undefined;

我的档案:

ActivationGuard.ts

import {Injectable} from '@angular/core';
import {Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';

@Injectable()
export class ActivationGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

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

        return this.userService.isUserAuthenticated
            .do(success => {
                if (!success) {
                    this.router.navigate(['/']);
                }
            });
    }
}

UserAuthenticationService.ts

import {Injectable, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from "rxjs/Observable";

@Injectable()
export class UserAuthenticationService implements OnInit {
    public isUserAuthenticated: Observable<boolean>;
    username: string = 'admin';

    constructor(private http: Http) {}


    ngOnInit(){
        this.isUserAuthenticated = this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .map(res => res.json())
            .share();
    }

}

期待任何形式的帮助。如果您有任何问题,请告诉我。谢谢。

0 个答案:

没有答案