gpt4 book ai didi

angular - 升级到 Angular 5 NullInjectorError : No provider for

转载 作者:行者123 更新时间:2023-12-04 01:58:05 26 4
gpt4 key购买 nike

我正在尝试升级到 Angular 4,但是在运行代码时出现错误:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthenticatedGuard -> AuthService]:
StaticInjectorError(Platform: core)[AuthenticatedGuard -> AuthService]:
NullInjectorError: No provider for AuthService!

该错误显示“没有 AuthService 提供者”,但在我正在导航的组件中,我注入(inject)并成功使用了我的 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 { }

认证的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;
}
}

应用程序路由.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 {}

这个错误可能神秘地来自哪里?我假设有些东西从 Angular 4 - 5 发生了变化,但我不确定是什么?

最佳答案

第一步:

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

第二步:
providers: [
AuthService
],

关于angular - 升级到 Angular 5 NullInjectorError : No provider for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com