简体   繁体   English

Angular 9:无法通过依赖注入创建 class,因为它没有 Angular 装饰器

[英]Angular 9 : The class cannot be created via dependency injection, as it does not have an Angular decorator

This error is driving me up a wall.这个错误把我逼到了墙角。 I have an authguard service as seen here.我有一个 authguard 服务,如此处所示。 No matter what I do the compiler keeps giving me this error无论我做什么,编译器都会一直给我这个错误

'
Either add the @Injectable() decorator to 'AuthGuard', or configure a different provider (such as a provider with 'useFactory').

' '

   @Injectable({ providedIn: 'root' })
    export class AuthGuard implements CanActivate {
constructor(private myService: MyService,
        private router: Router)}

and I am implementing it here in my app.module我正在我的 app.module 中实现它

providers: [  
    AuthGuard
]
bootstrap: [AppComponent]
})
export class AppModule { }

I clearly have the injectable decorator above the Authguard class but I still get this error.我显然在 Authguard class 上方有可注入装饰器,但我仍然收到此错误。 This only happened when I upgraded from Angular 8 to 9.1 Is this a bug of some sort with VS Code or the compiler or something?这只发生在我从 Angular 8 升级到 9.1 时,这是 VS Code 或编译器的某种错误还是什么?

You are registering same dependency from 2 places您正在从 2 个地方注册相同的依赖项

First is @Injectable({ providedIn: 'root' }) .首先是@Injectable({ providedIn: 'root' }) You are registering with root injector with this syntax { providedIn: 'root' } .您正在使用此语法{ providedIn: 'root' }根注入器注册。

Second is below you are registering again, that is the reason for your error.其次是在您再次注册的下方,这就是您出错的原因。

providers: [  
    AuthGuard
]

Just remove it from providers array and it will resolve your issue.只需将其从提供程序数组中删除,它就会解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM