升级到Angular 5 NullInjectorError:

时间:2018-03-14 12:02:20

标签: angular

我试图升级到角度4,但在运行代码时出现错误:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthenticatedGuard -> AuthService]: StaticInjectorError(Platform: core)[AuthenticatedGuard -> AuthService]: NullInjectorError: No provider for AuthService!

错误说"没有AuthService"的提供者,但在我从我注入并成功使用我的AuthService导航的组件中。以下是相关的源文件:

app.module.ts

import { AuthService } from '../../services/auth.service';
import { AuthenticatedGuard } from '../../utility/authenticated.gaurd'
@NgModule({
    imports:[ ... ],
    declarations: [ ... ], 
    providers: [ AuthService, AuthenticatedGuard ]})
export class AppModule { }

authenticated.gaurd.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service.js';

@Injectable()
export class AuthenticatedGuard implements CanActivate {

    constructor(private authService: AuthService, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        return true;
    }
}

APP-routing.module.ts

import { AdminComponent }       from '../../components/admin/admin.component';
import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: 'admin',  component: DashboardComponent, canActivate: [AuthenticatedGuard]},
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

export class AppRoutingModule {}

这个错误可能神秘地产生的任何想法?我假设某些东西从角度4 - 5发生了变化,但我不确定是什么?

2 个答案:

答案 0 :(得分:2)

改变这个:

import { AuthService } from '../services/auth.service.js';

对此:

import { AuthService } from '../services/auth.service';

authenticated.gaurd.ts 中的导入结尾处删除 .js 。导入不需要文件扩展名。

答案 1 :(得分:0)

第一步:

import { AuthService } from '../services/auth.service';

第二步:

providers: [
    AuthService
],