2017-12-27 79 views
0

我試圖總結每個router.navigateByUrl一類的函數實例化和打算調用相關地方的功能。但是這樣做拋出'Supplied參數不匹配任何調用目標的簽名'。我跟隨在這麼少的其他環節,但沒有一個似乎是有幫助的在我的情況提供的參數不匹配,調用對象的任何錯誤簽名會被拋出

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 { 
} 

回答

1

您的RouterComponent需要Router參數。路由器是一種可注射的,如果角知道如何處理你的RouterComponent類因而會分辨。

這將是最好的裝飾類爲Injectable,並在角分量注入價值。例如

import { Injectable } from '@angular/core';  
import { Router } from '@angular/router'; 

@Injectable() 
export class RouterService { 
    constructor(private router: Router) { } 

    homePage(){ 
    this.router.navigateByUrl('/home'); 
    } 
}; 

註冊它的模塊或依賴於Component裝飾添加到供應商領域,並將其導入您的組件。

import { Component } from '@angular/core'; 
import { RouterService } from '...'; 

@Component({ ... }) 
export class LoginComponent { 
    constructor(private router: RouterService) { } 

    toHomePage() { 
    this.router.homePage(); 
    } 
}; 

因爲它是一種注射,角知道如何解決的參數。

您爲RouterComponent類選擇命名常規會導致其他人認爲它被修飾爲角component,但您將其用作service

+0

謝謝,它解決了這個問題,我正在學習angular2,將瞭解有關@Injectable – brk

+0

只需要在提供程序中添加一個更新的RouterComponent – brk

+0

這是真的,但我只在答案中聲明,並未添加到代碼庫,因爲你也可以註冊在你的'NgModule'使用它在你所有的成分等,而無需將其聲明爲供應商的所有需要​​它的類。然而這幾類被註冊到同一模塊,以便角度來解決注射PARAMATERS。 –

相關問題