角度路由:无法进行重定向

时间:2018-05-23 22:00:23

标签: angular angular-router

这可能是一个非常常见的angular路由问题但是,我似乎无法使其正常工作。即使在通过角度文档之后,我也不确定我是否清楚地理解了所有概念。这是我想要实现的目标和我尝试过的目标:

我有一个登录应用程序。当用户在登录表单中单击“继续”时,我希望应用程序重定向到新的页面/应用程序。要做到这一点:

  1. 我首先尝试在RouterModule文件中的@NgModule imports列表中添加app.module.ts
  2. import { RouterModule, Routes } from '@angular/router';

    // Routes
    const routes: Routes = [
      {path: "", component: InvestigatorLoginComponent},
      {path: 'invdashboard', component: InvDashboardComponent}
    ];
    //...
    @NgModule({
    // ...
    imports: [
    // ...
    RouterModule.forRoot(
      routes, { enableTracing: true} // <= debugging
    ),
    // ...
    })
    export class AppModule {}
    
    1. <router-outlet></router-outlet>添加到<inv-dashboard>组件:
    2. app.component.html

      <div id='login-app-wrapper'>
        <nav-top></nav-top>
        <investigator-login></investigator-login> 
      </div>
      

      inv-dashboard.component.html

      <router-outlet></router-outlet>
      <p>
        inv-dashboard works!
      </p>
      

      inv-dashboard.component.ts

      import { RouterOutlet } from '@angular/router'; 
      
      @Component({
        selector: 'inv-dashboard',
        templateUrl: './inv-dashboard.component.html',
        styleUrls: ['./inv-dashboard.component.css']
      })
      export class InvDashboardComponent implements OnInit { // ... }
      
      1. 登录组件: investigator-login.component.html

         <form class='inv-login' [formGroup]="invLoginForm" (ngSubmit)="onSubmit(invLoginForm.value)">
        
         <mat-form-field class='inv-login-full-width-input'>
        
         <input matInput placeholder="Username" formControlName="fcUsername" value="" maxlength="30">
         </mat-form-field>
        
         <mat-form-field class='inv-login-full-width-input'>
         <input matInput placeholder="Password" formControlName="fcPassword" value="" maxlength="25">  
         </mat-form-field>
         <div class='prcd-btn-container'>
            <button mat-button color='primary' type='submit'>Proceed</button>
         </div>
        </form>
        
      2. investigator-login.component.ts

        `onSubmit(f: any): void {
            this.authenticator.postContent(f)
              .subscribe(
                this.handleLoginResponse,
                err => { throw new Error('failed'); } 
              );
          }
          handleLoginResponse(res: IResponseSuccess) {
            if(res.status === 200) {
              // success 
              console.log(res.template);
            }
            else {
              console.error('Server error ' + res.status);
            }
          }`
        

        填写表格后,我点击继续,没有任何反应。堆栈轨道不显示重定向。我是否需要将任何重定向代码添加到表单中的proceed按钮处理程序?我真的不确定还有什么要补充的。

        由于

2 个答案:

答案 0 :(得分:0)

在成功的任何地方都没有导航。在Router中注入constructor,如:

constructor(private router: Router) { }

然后导航成功

handleLoginResponse(res: IResponseSuccess) {
    if(res.status === 200) {
      // success 
      console.log(res.template);
      this.router.navigate(['/invdashboard']);
    }
    else {
      console.error('Server error ' + res.status);
    }
  }

答案 1 :(得分:0)

根据@YousefKhan的建议,我尝试了他发布的解决方案。它解决了我最初的问题。最初,问题在于我如何定义路由以及如何设置app.component.html文件,该文件应仅托管<router-outlet></router-outlet>组件。我已将app.component.html中的所有其他模板移至相关组件,并在Routes中添加了app.module.ts因此,在进行更改后:

app.module.ts Router

// Routes
const routes: Routes = [
  {path: "", redirectTo: "login", pathMatch: "full"},
  {path: "login", component: InvestigatorLoginComponent},
  {path: "dashboard", component: InvDashboardComponent}
];

app.component.html

<router-outlet></router-outlet>

这解决了路由问题,并帮助我更好地理解了这个概念。有关参考,请查看此文章on angular routing here.

我在评论中提到的另一个问题是this处理程序中的subscribe上下文未绑定到InvestigatorLoginComponent instance。简单的解决方案是使用arrow function。但是,由于我想将处理程序分开,我使用bindthis上下文添加到处理程序中。

investigator-login.component.ts

onSubmit(f: any): void {
this.authenticator.postContent(f)
  .subscribe(
    this.handleLoginResponse.bind(this),
    err => { throw new Error('failed'); } 
  );

}

希望它有所帮助。

相关问题