如果没有猫王操作员,angular2 在组件构造函数中注入路由器错误



当我的应用程序启动时,我希望默认显示路线/home。路由定义的"useAsDefault: true"属性尚未在我使用的 Angular 2 版本上实现。

为了解决这个问题,我想在app.component.ts中这样做(这是你在网上的许多例子中找到的):

export class AppComponent implements OnInit {
  constructor(private _router: Router) {}
  ngOnInit() {
    this._router.navigate(['/home']);
  }
}

但我得到:

"错误:(29, 12)TS2346:提供的参数与呼叫目标的任何签名都不匹配。

如果我添加猫王运算符,它可以工作,我没有收到任何错误:

export class AppComponent implements OnInit {
  constructor(private _router?: Router) {}
  ngOnInit() {
    this._router.navigate(['/home']);
  }
}

有人可以帮助我理解为什么吗?My app.component.ts 文件:

import {Component, OnInit} from '@angular/core';
import {Router, Routes, ROUTER_DIRECTIVES } from '@angular/router';
import {NavbarComponent} from "./navbar.component";
import {UsersComponent} from "./users.components";
import {PostsComponent} from "./posts.component";
import {HomeComponent} from "./home.component";
@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html',
    directives: [NavbarComponent, ROUTER_DIRECTIVES]
})
@Routes([
  {path: '/home', component: HomeComponent},
  {path: '/users', component: UsersComponent},
  {path: '/posts', component: PostsComponent}
])
export class AppComponent implements OnInit {
  constructor(private _router?: Router) {}
  ngOnInit() {
    this._router.navigate(['/home']);
  }
}

如果我添加猫王运算符,它可以工作,我没有收到任何错误

次要:这不称为猫王运算符。它只是表示可选参数的语法(参考 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3922-parameter-list)

有人可以帮助我理解为什么

该错误Supplied parameters do not match any signature of call target指出这样一个事实,即某些东西正在调用构造函数而没有提供所有参数。该代码未显示在您的问题中,但您现在知道原因(当您将参数标记为可选时,出于显而易见的原因,您会静音该错误)

最新更新