Angular 4 Перенаправление на ngOnInit

Я работаю в приложении 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 { }

person Karthikeyan    schedule 29.12.2017    source источник


Ответы (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}
        ]
    }
]
person LLai    schedule 29.12.2017