Angular 4重定向到ngOnInit

时间:2017-12-29 14:08:11

标签: angular angular4-router

我在Angular 4应用程序中工作。我想在加载app.component之前授权用户(即使不应该初始化此app.component),如果未通过检查API授权,将重定向到未授权页面,并在用户有效时重定向到实际页面。

这就是我所做的。如果用户有效且未重定向到未经授权的页面,我不会重定向应用程序组件页面。

AuthorizationComponent.ts

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { Router } from "@angular/router";

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

  constructor(private router: Router) { }

  ngOnInit() {
    alert('auth component and redireting to /app')
    // API Call goes here,
    If(UserIsInValid)
       this.router.navigate['/UnAuthorized']
    else
      this.router.navigate['/app']

  }

  ngOnDestroy()
  {
    alert('auth destroy')
  }

  ngAfterViewInit()
  {
    alert('auth after init')        
  }

}

AuthorizationComponent.html

<router-outlet></router-outlet>

app.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, RouterModule } from '@angular/router';


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

constructor(private _router: Router) {
  }

  ngOnInit(): void {}
  }

app.component.html

 <nav>
      <a routerLink="/component-one">Component One</a>
      <a routerLink="/component-two">Component Two</a>
    </nav>

    <router-outlet></router-outlet>

我有app.routing.ts

 import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { FirstComponent } from './FirstComponent';
import { SecondComponent } from './SecondComponent';
import { AppComponent } from "./app.component";
 import { ErrorComponent } from "./error.component";
import { AuthorizationComponent } from "./shared/authorization/authorization.component";

const routes: Routes = [
    { path: '', component: AuthorizationComponent, pathMatch: 'full' },
    {
        path: 'app',component:AppComponent,
        children: [
            {path:'', redirectTo:'First', pathMatch: 'full'},
            {path:'First', component: FirstComponent},
            {path:'Second', component: SecondComponent}
            //{path:'', component: FirstComponent}
        ]
    },

    { path: 'NotFound', component: ErrorComponent },
    { path: 'Error', component: ErrorComponent },
    { path: 'UnAuthorized', component: ErrorComponent },
    { path: '**', redirectTo: 'NotFound' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
})
export class AppRoutingModule { }

export const routingComponents = [FirstComponent, SecondComponent];

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { routingComponents, AppRoutingModule } from './app.routing';
import { AuthorizationComponent } from './shared/authorization/authorization.component';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents,
    AuthorizationComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule    
  ],
  providers: [

  ],
  bootstrap: [AuthorizationComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:1)

您应将支票移至CanActivate Guard

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router){}

    canActivate(): boolean {
        if(UserIsInValid){
            // user is invalid. redirect to unauthorized route
            this.router.navigate['/UnAuthorized'];
            return;
        } else {
            // user is valid, continue to route
            return true;
        }
    }
}

现在您可以将警卫附加到任何需要保护的路线

const routes: Routes = [
    {
        path: 'app',component:AppComponent,
        canActivate: [ AuthGuard ],
        children: [
            {path:'', redirectTo:'First', pathMatch: 'full'},
            {path:'First', component: FirstComponent},
            {path:'Second', component: SecondComponent}
        ]
    }
]