簡體   English   中英

Angular 4,路由器4.0.0:routerLink或router.navigate不會以編程方式重定向到子路由

[英]Angular 4, Router 4.0.0: routerLink or router.navigate programatically doesn't redirect to child routes

我正在嘗試創建一個鏈接,以在登錄(/登錄路由)后重定向到/ dashboard / overview子路由而沒有任何運氣。 我單擊鏈接,沒有錯誤也沒有任何回應。 我可以在瀏覽器的底部欄中看到正確的路徑,如果手動輸入URL,則訪問正確的頁面,路由為/ 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' }

]

我什至將console.log放在儀表板組件的ngOnInit上,以查看是否已創建該組件,或者在概述組件中,但是我沒有任何運氣,當以編程方式導航或使用導航時,我在控制台上看不到任何消息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()方法僅返回具有用戶auth狀態的observable。 我想知道是否存在爭用條件或什么...導致可觀察性最初是通過發出http異步請求來設置的。...如果我將console.log放在isAuthenticated方法中,它將被記錄在控制台上。 如果我將console.log放進或放出authguard函數的映射內,則如果未記錄,則由於某種原因未執行代碼。

驗證服務

    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上的主題,因為它使我獲得了最后發出的值,這與必須訂閱的常規主題相比是一個很酷的功能,有時這還不夠。 以下是我的答案的更多詳細信息。

最后,問題出在authService在isAuthenticated()方法上返回的內容,我顯然沒有根據日志返回已解析的值,因此authguard在能夠解析到組件的路由之前被卡住了。 我通過搜索rxjs文檔解決了我的問題。 我發現了BehaviorSubject https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md

它可以讓您獲取最后一次發出的值,這樣我就可以返回Observable.of(userIsAuthenticated.getValue())並將其傳遞給AuthGuard,並且現在可以正常使用了。 我添加了邏輯,如果最后發出的值是false,那么我將執行一個虛擬請求,以決定是否應將用戶發送到登錄屏幕。 然后這與將BehaviourSubject的值更改為false緊密結合,如果我對服務器發出的每個請求均收到HTTP禁止響應。 這些內容的結合將確保前端和后端傳統會話之間的一致性,避免后端上的過期會話和前端上的未過期狀態。 希望這對某人有幫助。 編碼:

驗證服務

        @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' }

]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM