无法验证Angular 5

时间:2018-04-12 04:29:31

标签: angular typescript angular2-routing

应用程序应在身份验证后转移到另一个页面。但由于某种原因在日志中写道所有Ok认证都通过了。但是没有发生到另一个页面的转换。可能是什么问题?

auth.guard.ts:

import { Injectable }     from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {Angular2TokenService} from "angular2-token";

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authTokenService:Angular2TokenService,
              private router:Router){}

  canActivate() {
    if (localStorage.getItem('currentUser')) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page
    this.router.navigate(['/sign_in']);
    return false;
}

}

auth.service.ts:

import { Injectable } from '@angular/core';
import {Angular2TokenService} from "angular2-token";
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {Response} from "@angular/http";

@Injectable()
export class AuthService {

  userSignedIn$:Subject<boolean> = new Subject();

  constructor(private authService:Angular2TokenService) {
    this.userSignedIn$.next(this.authService.userSignedIn());
  }

  logOutUser():Observable<Response>{

    return this.authService.signOut().map(
        res => {
          this.userSignedIn$.next(false);
          return res;
        }
    );
  }

  logInUser(signInData: {email:string, password:string}):Observable<Response>{

    return this.authService.signIn(signInData).map(
        res => {
          this.userSignedIn$.next(true);
          return res
        }
    );

  }

   registerUser(signUpData:  {email:string, password:string, passwordConfirmation:string}):Observable<Response>{
    return this.authService.registerAccount(signUpData).map(
        res => {
          this.userSignedIn$.next(true);
          return res
        }
    );
  }

}

登录-in.component.ts:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { AuthService } from "../../services/auth.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {

  signInUser = {
    email: '',
    password: ''
  };

  @Output() onFormResult = new EventEmitter<any>();

  constructor(private _router: Router, private authService:AuthService) { }

  ngOnInit() {}

  onSignInSubmit(){

    this.authService.logInUser(this.signInUser).subscribe(

        res => {
          if(res.status == 200){
            // loginForm.resetForm();
            this.onFormResult.emit({signedIn: true, res});
            this._router.navigate(['user_profile']);
          }
        },

        err => {
          console.log('err:', err);
          // loginForm.resetForm();
          this.onFormResult.emit({signedIn: false, err});
        }
    )

  }




}

登录-in.component.html:

<div class="main-content">
        <form (ngSubmit)="onSignInSubmit()" #f="ngForm" >


                <div class="row">

                  <div >
                    <input id="email"
                           type="email"
                           required
                           name='email' 
                           [(ngModel)]="signInUser.email" 
                           class="validate">

                    <label for="email">Email</label>
                  </div>


                  <div >
                    <input id="password" 
                           type="password" 
                           required  
                           name='password' 
                           [(ngModel)]="signInUser.password" 
                           class="validate">

                    <label for="password">Password</label>
                  </div>

                  <div >
                    <button type="submit" 
                    > 
                      Login </button>
                  </div>


                </div>

              </form>

</div>

2 个答案:

答案 0 :(得分:0)

user_profile中的路径错误,请尝试以下操作

 this._router.navigate(['/user_profile']);

答案 1 :(得分:0)

如果你的auth guard在你的'user_profile'路径上;那么你需要在localStorage中设置'currentUser'。否则,你的警卫只会重定向回到登录页面。