routerOnActivate在Angular 4上

时间:2017-08-01 19:30:03

标签: angular

我在Angular 2应用程序上有这样的组件,但它没有在Angular 4上运行,RouteSegment不起作用。如何在Angular 4上做到这一点?

export class CallBackLoginComponent {

private user: User = new User();
private showLoading: boolean = false;
private errorMessage: string = null;

constructor(private _loginService: LoginService,
    private _router: Router,
    private userService: UserService,
    private _comunication: Comunication,
    private _routerParams: RouteSegment) {
};

//Parametros recebidos atraves da rota /user/token
routerOnActivate(curr: RouteSegment) {
    var token = {token: curr.getParam('token')};
    if (token != null) {
        this.showLoading = true;
        this.errorMessage = null;

        this.userService.vldToken(token).subscribe(
            result => this.onLoginResult(result),
            error => this.onLoginError(error)
        );
    }
    else{
        this._router.navigate(['/']);
    }
}

2 个答案:

答案 0 :(得分:0)

该版本的路由器用于早期的Releases Candidates。在RC 4和RC5之间对路由器进行了重大改写(将其更新为版本3)。

现在您必须订阅route.params并获取您正在寻找的密钥令牌。

export class CallBackLoginComponent implements OnInit {

   private user: User = new User();
   private showLoading: boolean = false;
   private errorMessage: string = null;

constructor(private _loginService: LoginService,
    private _route: ActivatedRoute,
    private _router: Router,
    private userService: UserService,
    private _comunication: Comunication) {
};

ngOnInit() {
   this._route.params().subscribe(params => this.routerOnActivate(params['token']);
}

//Parametros recebidos atraves da rota /user/token
routerOnActivate(token: string) {
    if (token != null) {
        this.showLoading = true;
        this.errorMessage = null;

        this.userService.vldToken(token).subscribe(
            result => this.onLoginResult(result),
            error => this.onLoginError(error)
        );
    }
    else{
        this._router.navigate(['/']);
    }
}

答案 1 :(得分:0)

您可以通过两种方式实现:

  1. 使用路由器的canActivate功能。
  2. app.routing.ts

    import { HomeComponent } from './user/home.component';
    import { AppGuard } from './app.gaurd';
    import { UserComponent } from './user/user.component';
    import { RouterModule, Routes } from '@angular/router';
    const usrRoutes: Routes = [
      {
        path: 'user/:token', component: UserComponent
        , canActivate: [AppGuard]
      },
      {
        path:'home',component:HomeComponent
      },
      { path: '**', redirectTo: 'home' }
    ];
    
    export const userRouting = RouterModule.forRoot(usrRoutes, { useHash: true }); 
    

    app.guard.ts

    import { element } from 'protractor';
    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    @Injectable()
    export class AppGuard implements CanActivate {
      constructor(private router: Router) { }
    
      /**
       * 
       * @param route  current route object
       * @param state  route state
       */
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot
       ) {
        let paramJSON = route.paramMap['params'];
        if (paramJSON['token']) {
        let token = paramJSON['token'];
        if (token && token != null) {
         // do your operation or api call to validate token 
         return true;
        } else {
          /**
           *  return url , redirect where u want to redirect after failure 
           */
           this.router.navigate(['/home'], { queryParams: { returnUrl: state.url }});
         }
         return false;
      }
    }
    

    app.module.ts:import AuthGard&路线到模块

        @NgModule({
          declarations: [
            AppComponent,
            UserComponent,
            HomeComponent
          ],
          imports: [
            HttpModule,
            BrowserModule,
            userRouting,
          ],
          providers: [
            AppGuard
          ],
          bootstrap: [AppComponent]
        })
        export class AppModule { }
    
    1. 使用ngOnInit功能
    2. 这里我们不需要使用canActivate,在组件中使用此代码....

      import { ActivatedRoute, Params, Router } from '@angular/router';
      import { Component, OnInit } from '@angular/core';
      
      @Component({
          selector: 'app-user',
          templateUrl: './user.component.html'
      })
      export class UserComponent implements OnInit {
      
      
          constructor(
              private route: ActivatedRoute,
              private router: Router
          ) {
      
          }
      
          ngOnInit() {
              this.checkRouteParam_();
          }
      
          /**
              *  this will be called every time route changes
                 so you can perform your functionality here
              */
          public checkRouteParam_() {
              this.route.params.subscribe((params: Params) => {
                  this.validateRouteParam();
      
              });
          }
      
      
          public validateRouteParam() {
              let token = this.route.snapshot.params['token'];
              if (token) {
                  // do your operation or api call to validate token 
                  return true;
      
              } else {
                  let failureRetUrl = "/home";
                  /**
                   *  return failureRetUrl , redirect where u want to redirect after failure 
                   */
                  return this.router.navigate([failureRetUrl]);
              }
      
          }
      
      }