角路由器不会激活ngoninit

时间:2019-02-22 14:07:49

标签: angular signalr angular-router ngoninit

我有一个角度应用程序,它想为用户创建一个GUI登录。 我有一个带有以下html代码的登录组件

<mat-card>
  <mat-form-field class="full-width">
    <input matInput placeholder="Enter your Username" [(ngModel)]="username">
  </mat-form-field>

  <mat-form-field class="full-width">
    <input matInput placeholder="Enter Password" [(ngModel)]="password">
  </mat-form-field>

  <button mat-raised-button (click)="logIn()">Log In</button>
</mat-card>

这是组件的代码

@Hub({hubName: 'DALHub'})
export class LogInComponent implements OnInit {
  private hubWrapper: HubWrapper;
  username: String = '';
  password: String = '';

  constructor(private router: Router, private hub: HubService) {
    // This is signalr init process
    this.hubWrapper = this.hub.register(this);
    this.hub.connect({url: 'http://localhost:10476/signalr'});
  }

  ngOnInit() {
  }

  logIn() {
    this.hubWrapper.invoke('LogIn', this.username, this.password);
  }

  @HubSubscription()
  LogOK() {
    this.hubWrapper.unregister();
    this.router.navigate(['logged', this.username, this.password]);
  }
}

如您所见,我正在为客户端使用信号器服务器和ngx-signalr软件包。

用户单击“登录”按钮后,将激活登录功能,该功能将调用服务器以检查用户名和密码是否正确。 如果密码和用户名正确,则服务器将在客户端中调用LogOK函数,以将应用程序路由到其他组件。

这是路由器配置

const routes: Routes = [
  {path: '', component: LogInComponent},
  {path: 'logged/:username/:password', component: UserComponent}
]; 

(请注意,路由器插座位于应用html页面中)

这是登录视图log in component 当我登录时,我希望得到以下页面 UserComponent 但是,当我登录时会看到以下页面 LogIn results 如您所见,登录页面仍然在这里,用户页面看起来很奇怪,我检查了一下,发现UserComponent的ngOnInit函数没有被激活,我认为这就是问题所在。 你知道我该怎么解决吗?

2 个答案:

答案 0 :(得分:0)

似乎路由路径错误,因此请在login component中更改路由

const url = `${'logged/' + this.username + '/' + this.password}`;
this.router.navigate([url]);

答案 1 :(得分:0)

路由配置

const routes: Routes = [
  {path: '', component: LogInComponent},
  {path: 'logged/:username/:password', component: UserComponent}
]; 

路线导航/激活

this.router.navigate(['/logged', this.username, this.password]);

您好像错过了斜线吗?注意路径前面的斜线。

从文档中

  

在构建危机中心功能时,您导航到了   危机详细信息路径使用以斜杠开头的绝对路径。

     

路由器将此类绝对路径与从顶部开始的路由进行匹配   路由配置。

此外,您可以考虑启用路由跟踪,以便更好地了解路由可能存在的问题:

RouterModule.forRoot([routes], { enableTracing: true })