当我尝试在我的类的构造函数中声明Router时,它抛出无法在运行时解析所有参数。但是如果我在普通(private router: Router
)外部构造函数中声明它,它不会抛出任何错误,但是当我点击链接时,它会在EXCEPTION: Cannot read property 'navigate' of undefined
处抛出this.router.navigate()
。
//Error: (SystemJS) Can't resolve all parameters for DataBindService: (?).(…)
constructor(private router: Router) {
}
//EXCEPTION: Cannot read property 'navigate' of undefined
private router: Router;
//full class
/// <reference path="AddedVariables.d.ts" />
import { Router } from '@angular/router';
export class DataBindService {
private router: Router;
constructor(private router: Router) {
}
moveToAnotherPage(value: string) {
this.router.navigate([value], { skipLocationChange: true });
}
}
添加了模块和服务编码。 交换服务是在NgModule中提供的,其中包含我的导航方法。
//NgModule where Router is in provides
import {NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {APP_BASE_HREF} from '@angular/common';
import { RouterModule, Router} from '@angular/router';
import {SwapService} from "./services/SwapService";
@NgModule({
imports: [ BrowserModule ,RouterModule.forRoot([
{ path: '', component: Swap },
{ path: 'first', component: First },
{ path: 'secound', component: Secound },
{ path: 'third', component: Third }
])
],
declarations: [ AppComponent, Swap, First, Secound, Third],
providers: [{provide: APP_BASE_HREF, useValue : '/' }, SwapService ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
//the service class which have the this.router.navigate()
/// <reference path="AddedVariables.d.ts" />
import {Router} from "@angular/router";
export class SwapService {
constructor(private router: Router) { }
moveToAnotherPage(value: string) {
console.log('value:%o', value);
this.router.navigate([value], {skipLocationChange: true});
}
}
答案 0 :(得分:0)
通过将服务作为@Injectable()来解决这个问题。问题是我没有提供我的服务@Injectable(),我的服务是一个简单的打字稿类。
/// <reference path="AddedVariables.d.ts" />
import {Router} from "@angular/router";
import {Injectable} from "@angular/core";
@Injectable()
export class SwapService {
constructor(private router: Router) { }
moveToAnotherPage(value: string) {
console.log('value:%o', value);
this.router.navigate([value], {skipLocationChange: true});
}
}