我试图将每个router.navigateByUrl
包装在一个类的函数中,并计划在相关位置调用该函数。但这样抛出'提供的参数与呼叫目标的任何签名都不匹配'。我在SO中跟踪了一些其他链接但在我的情况下似乎没有任何帮助
commonRouter.ts
// have wrapped navigation to home in homePage
// so wherever is needed this homePage will be called instead of
//this.router.navigateByUrl('/home');
import {Router} from '@angular/router';
export class RouterComponent{
router:any;
constructor(private rt:Router){
this.router=rt;
}
homePage(){
this.router.navigateByUrl('/home');
}
}
someComponent.ts
// Importing the newly created typescript file
import {RouterComponent} from './../../app-routing-component';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
private ms:MainService= new MainService();
//Instantiating RouterComponent
private rt:RouterComponent = new RouterComponent(); // this line throwing error
constructor(private fb:FormBuilder) {}
someMethod(){
rt.homePage() // Calling homePage
}
//... rest of code
}
APP-routing.module.ts
// module where all the paths and component are declared
import {NgModule} from "@angular/core";
import {RouterModule, Routes} from "@angular/router";
import {HomeComponent} from "./home/home/home.component";
const routes: Routes = [
{
path: 'login', component: LoginComponent,
}, {
path: 'home', component: HomeComponent,
children: [{
path: "account",
component: AccountsComponent
},{
path: '**',
component: PageNotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
答案 0 :(得分:1)
您的Opened F3
需要RouterComponent
个参数。路由器是一个可注入的,因此如果Angular知道如何处理你的RouterComponent类,它将是可解析的。
最好将您的类装饰为Router
并将值注入Angular组件。 e.g。
Injectable
在您的模块中注册它或将其作为依赖项添加到import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class RouterService {
constructor(private router: Router) { }
homePage(){
this.router.navigateByUrl('/home');
}
};
装饰器中的providers字段,并将其导入您的组件。
Component
因为它是Injectable,Angular知道如何解析参数。
为import { Component } from '@angular/core';
import { RouterService } from '...';
@Component({ ... })
export class LoginComponent {
constructor(private router: RouterService) { }
toHomePage() {
this.router.homePage();
}
};
课程选择命名惯例会导致其他人认为它被装饰为Angular RouterComponent
,但您将其用作component
。