Angular 4,Router 4.0.0:routerLink或router.navigate以编程方式不会重定向到子路由

时间:2017-06-14 04:31:20

标签: javascript angular url-redirection angular-router

我正在尝试创建一个链接,以便在登录(/ signin route)后重定向到/ dashboard / overview子路由,但没有任何运气。我点击链接,我没有错误也没有任何回复。我可以在浏览器底部栏上看到正确的路径,如果我手动输入网址,则访问正确的页面,路径为 / dashboard / overview 。有一件事我不确定它是否有任何关系,路由是AuthGuarded。

我在登录后将用户重定向到仪表板后以编程方式尝试了,我甚至可以在Chrome控制台上看到“重定向到仪表板”消息

onSignin(form: NgForm){
    const email = form.value.email;
    const password = form.value.password;
    this.user = {email, password};
     this.authServiceSubscription = this.authService.signinUser(this.user).subscribe(
       (response) => {
         //redirect to dashboard
        const loginResultCode = response.login_result_code;
         if (loginResultCode == "SUCCESS") {
                       console.log("Sponsor logged in");
                       this.authService.changeStatusToAuthenticated();
                       //redirect to dashboard
                       console.log('Redirecting to dashboard');
                       this.router.navigate(['/dashboard/overview']);
                   } else {
                       console.log("There were errors with the data");
                       //present errors to the user
                       this.errorMessage = "Los datos de autenticación son incorrectos. Intente nuevamente";
                   }
       },
       (error) => { console.log("Error Login", error); this.errorMessage = "Hubo un error interno, intente de nuevo mas tarde";}
       );
  }

还创建了一个routerLink,但它也不起作用,没有任何反应,甚至在控制台中都没有错误:

  <li><a style="cursor: pointer;" routerLink="/dashboard/overview">Go To Dashboard</a></li>

这是我的路由文件:

const appRoutes: Routes = [
  { path: '', redirectTo: '/', pathMatch:'full'},
  { path: '', component: MainComponent },
  { path: 'signin', component:SigninComponent},
  { path: 'signup', component: SignupComponent},
  { path: 'dashboard', canActivate:[AuthGuard],component: DashboardComponent,
    children: [
      { path: '', redirectTo:'/dashboard/overview', pathMatch: 'full'},
      { path: 'overview', component: OverviewCampaignsComponent },
      { path: 'active', component: ActiveCampaignsComponent},
      { path: 'history', component: HistoryCampaignsComponent}
    ] },
  { path: 'not-found', component: ErrorPageComponent },
  { path: '**', redirectTo: '/not-found' }

]

我甚至在控制台组件的ngOnInit上放置了一个console.log以查看组件是否已创建,或者在概述组件中,但我没有运气,导航时我在控制台上看不到任何消息以编程方式和routerLink。当我按照上面的说明手动访问时,我确实收到了消息。有任何想法吗?非常感谢你

编辑:显然我正在应用于仪表板路由的authguard存在问题,这是AuthGuard文件,可能是因为它没有捕获到某些错误,或者返回的值不是那些应该是? :

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


@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.authService.isAuthenticated().map(isAuth => {
      if (isAuth){
        console.log("Auth Guard approves the access");
        return true;
      }
      else {
        console.log('AuthGuard Denying route, redirecting to signin');
        this.router.navigate(['/signin']);
        return false;
      }
    });
  }
}

authService上的isAuthenticated()方法只返回一个具有用户身份验证状态的observable。我想知道是否存在竞争条件或者什么......因为最初通过发出http异步请求来设置observable ....如果我在isAuthenticated方法中放入console.log它会在控制台上登录。如果我在authguard函数的地图中放入一个console.log,如果它没有被记录,那么由于某种原因代码没有被执行....

auth.service.ts

    import { Injectable, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { Http, Response, RequestOptions, Headers } from '@angular/http';
    import 'rxjs/add/operator/map';
    import {Observable, Subject} from "rxjs/Rx";

    @Injectable()
    export class AuthService implements OnInit {
     userIsAuthenticated = new Subject();
      constructor(private router: Router, private http: Http) {
        this.ngOnInit();
      }

      private getHeaders(){
          let headers = new Headers();
          headers.append('Content-Type', 'application/json');
          headers.append('Accept', 'application/json');
          headers.append('Authorization','Bearer');
          return headers;
      }

      ngOnInit(){

        this.changeStatusToUnauthenticated();
        //initial check with the server
        let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });

       this.http.get('http://localhost:3000/api/sponsor/check/login',options)
          .map(response => {
        console.log("Execute this");
            if (response.status === 200) {
              console.log("execute also this");
              this.changeStatusToAuthenticated();
              return Observable.of(true);
            }
          }
        ).catch((err)=>{
          //maybe add in the future if the code is 403 then send him to login otherwise send him elsewhere
          if(err.status === 403){
            console.log('Forbidden 403');
    //        If I want to redirect the user uncomment this line
    //        this.router.navigate(['/signin']);
          }
          this.changeStatusToUnauthenticated();
          return Observable.of(false);
        }).subscribe((isAuth)=>{
           console.log("Initial refresh auth state ", isAuth);
        });

      }

      isAuthenticated(): Observable<boolean> {
  if(this.userIsAuthenticated){
 //if I change this line for return Observable.of(true) it works
   return this.userIsAuthenticated;
 }else{
   return Observable.of(false);
 }
  }

      logout() {
        console.log('logging out');
        let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });
        return this.http.get('http://localhost:3000/api/sponsor/logout/', options).map(res=>res.json())
        .subscribe(
            (response) => {
              //redirect to dashboard
             const logoutResultCode = response.code;
              if (logoutResultCode == "200") {
                            console.log("Sponsor logged out successfully");
                            //redirect to dashboard
                            this.changeStatusToUnauthenticated();
                            this.router.navigate(['/signin']);
                        }
            },
            (error) => {
              console.log("Error Logout- Header", error);
              //check for 403 if it's forbidden or a connection error
              this.changeStatusToUnauthenticated();
              this.router.navigate(['/signin']);}
          );

      }

      signinUser(user) {
        console.log("Logging user");
        let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });
        return this.http.post('http://localhost:3000/api/sponsor/login/', user, options).map(
          response => response.json());
      }

      registerUser(user) {
        let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });
        return this.http.post('http://localhost:3000/api/sponsor/register/', user, options).map(
          response => response.json());
      }

      changeStatusToUnauthenticated(){
        this.userIsAuthenticated.next(false);
      }

      changeStatusToAuthenticated(){
        this.userIsAuthenticated.next(true);
      }


    }

编辑2:我在authService上使用了行为主题而不是主题,因为它让我获得最后一次发现的值,与您必须订阅的常规主题相比,这是一个非常酷的功能,有时这是不够的。关于我的答案的更多细节如下。

1 个答案:

答案 0 :(得分:1)

最后问题出在autAService在isAuthenticated()方法上返回的内容,我没有明显地根据日志返回一个已解析的值,因此在能够解析到组件的路由之前,authguard被卡住了。我通过搜索rxjs文档解决了我的问题。我找到了BehaviorSubject https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md

它允许您获取最后一个值emmited,因此我可以返回一个Observable.of(userIsAuthenticated.getValue())并将其传递给AuthGuard,它现在可以正常工作。我添加了一个逻辑,如果最后一个发出的值是假的,那么我做一个虚拟请求来决定是否应该将用户发送到登录屏幕。然后,如果我在服务器上发出的每个请求都得到一个http禁止响应,那么这会将BehaviourSubject的值更改为false。这些结合起来将确保前端和后端传统会话之间的一致性,避免后端上的过期会话和前端的非过期状态。希望这有助于某人。代码:

<强> auth.service.ts

        @Injectable()
        export class AuthService implements OnInit {
         userIsAuthenticated= new BehaviorSubject(null);
          constructor(private router: Router, private http: Http) {
            this.ngOnInit();
          }

          private getHeaders(){
              let headers = new Headers();
              headers.append('Content-Type', 'application/json');
              headers.append('Accept', 'application/json');
              headers.append('Authorization','Bearer');
              return headers;
          }


      ngOnInit() {
        //initial check with the server
        this.doAuthCheck();

      }

      doAuthCheck(): Observable<boolean> {

        let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });

        return this.http.get('http://localhost:3000/api/check/login', options)
          .map(response => {
            if (response.status === 200) {
              this.changeStatusToAuthenticated();
              return Observable.of(true);
            }
          }
          ).catch((err) => {
            //maybe add in the future if the code is 403 then send him to login otherwise send him elsewhere
            if (err.status === 403) {
              console.log('Forbidden 403');
              //        If I want to redirect the user uncomment this line
              //        this.router.navigate(['/signin']);
            }
            this.changeStatusToUnauthenticated();
            return Observable.of(false);
          });
      }

      isAuthenticated(): Observable<boolean> {
        const isAuth = this.userIsAuthenticated.getValue();
        if (isAuth) {
          return Observable.of(isAuth);
        } else {
          return this.doAuthCheck();
        }
      }


  logout() {
    console.log('logging out');
    let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });
    return this.http.get('http://localhost:3000/api/logout/', options).map(res => res.json())
      .subscribe(
      (response) => {
        //redirect to dashboard
        const logoutResultCode = response.code;
        if (logoutResultCode == "200") {
          console.log("logged out successfully");
          //redirect to dashboard
          this.changeStatusToUnauthenticated();
          this.router.navigate(['/signin']);
        }
      },
      (error) => {
        console.log("Error Logout- Header", error);
        //check for 403 if it's forbidden or a connection error
        this.changeStatusToUnauthenticated();
        this.router.navigate(['/signin']);
      }
      );

  }



  signinUser(user) {
    console.log("Logging user");
    let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });
    return this.http.post('http://localhost:3000/api/login/', user, options).map(
      response => response.json());
  }

  registerUser(user) {
    let options = new RequestOptions({ headers: this.getHeaders(), withCredentials: true });
    return this.http.post('http://localhost:3000/api/register/', user, options).map(
      response => response.json());
  }

changeStatusToUnauthenticated() {
    this.userIsAuthenticated.next(false);
  }

  changeStatusToAuthenticated() {
    this.userIsAuthenticated.next(true);
  }

        }

<强> AUTH-guard.service.ts

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


@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.authService.isAuthenticated().map(isAuth => {
      console.log("is Authenticated",isAuth);
      if (isAuth){
        console.log("Auth Guard approves the access");
        return true;
      }
      else {
        console.log('AuthGuard Denying route, redirecting to signin');
        this.router.navigate(['/signin']);
        return false;
      }
    });
  }
}

路由文件

const appRoutes: Routes = [
  { path: '', redirectTo: '/', pathMatch:'full'},
  { path: '', component: MainComponent },
  { path: 'signin', component:SigninComponent},
  { path: 'signup', component: SignupComponent},
  { path: 'dashboard', canActivate:[AuthGuard],component: DashboardComponent,
    children: [
      { path: '', redirectTo:'/dashboard/overview', pathMatch: 'full'},
      { path: 'overview', component: OverviewCampaignsComponent },
      { path: 'active', component: ActiveCampaignsComponent},
      { path: 'history', component: HistoryCampaignsComponent}
    ] },
  { path: 'not-found', component: ErrorPageComponent },
  { path: '**', redirectTo: '/not-found' }

]