Ada*_*m S 6 components dependency-injection angular
我开始使用Angular2应用程序,自从几天起我就遇到了问题!
Can't resolve all parameters for HomeComponent: (?).(…)
Run Code Online (Sandbox Code Playgroud)
但我的问题不是特定的提供者:我尝试在HomeComponent构造函数中注入的每一个都返回该错误.没有关于错误的类似问题解决了我的情况,现在我花了很多时间寻找这个,我找不到它.
App.moodule.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { SimpleNotificationsModule } from 'angular2-notifications';
// Controllers
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home.component';
// Service
import { AuthService } from './services/auth.service';
// Guards
import { AuthGuard } from './guards/auth.guard';
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: '',
component: HomeComponent,
canActivate: [AuthGuard]
}
]),
SimpleNotificationsModule
],
declarations: [
AppComponent,
HomeComponent
],
providers: [
AuthGuard,
AuthService,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
我的主页成员:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NotificationsService } from 'angular2-notifications';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'home',
templateUrl: '/templates/home.html'
})
export class HomeComponent implements OnInit
{
public test: boolean = false;
constructor(
private _authService: AuthService
) {}
ngOnInit()
{
this.test = true;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试导入的AuthService是空的,正如我所说,我在HomeComponent中注入的每个提供程序都返回该错误.每个构造函数参数在错误中创建一个新问号.如果您需要更多代码,请告诉我,但我不认为其余的(模板,systemjs.config.js ...)是问题
Xea*_*lot 10
确保你有
"emitDecoratorMetadata": true,
Run Code Online (Sandbox Code Playgroud)
在你的tsconfig.js.@Inject()如果已启用,则不需要添加到函数参数中.
导入这个
import {Inject} from '@angular/core';
Run Code Online (Sandbox Code Playgroud)
并将构造函数更改为
constructor(@Inject(AuthService) _authService: AuthService)
{
}
Run Code Online (Sandbox Code Playgroud)
在使用它之前,你应该@Inject任何服务到构造函数.
并且您的服务应该是可注射的
@Injectable()
export class AuthService {
}
Run Code Online (Sandbox Code Playgroud)