简体   繁体   English

ngOnInit 上的 Angular 4 重定向

[英]Angular 4 Redirecting on ngOnInit

I am working in the Angular 4 application.我正在 Angular 4 应用程序中工作。 I wants to authorize a user before loading the app.component(even this app.component should not be initialized) and will redirects to unauthorized page if not authorized by checking API, and will redirect to the actual page when user is valid.我想在加载 app.component 之前授权用户(即使这个 app.component 不应该被初始化),如果没有通过检查 API 授权,将重定向到未经授权的页面,并在用户有效时重定向到实际页面。

This the way what I have done.这就是我所做的。 I am not redirecting the app component page if user is valid and not redirecting to unauthorized page.如果用户有效并且没有重定向到未经授权的页面,我不会重定向应用程序组件页面。

AuthorizationComponent.ts授权组件.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授权组件.html

<router-outlet></router-outlet>

app.component.ts 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应用程序组件.html

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

    <router-outlet></router-outlet>

I have a app.routing.ts我有一个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 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 { }

You should move your check into a CanActivate Guard您应该将支票转移到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;
        }
    }
}

Now you can attach the guard to any route that needs to be protected现在您可以将防护装置附加到任何需要保护的路线上

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM