简体   繁体   中英

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. 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

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

I clearly have the injectable decorator above the Authguard class but I still get this error. 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?

You are registering same dependency from 2 places

First is @Injectable({ providedIn: 'root' }) . You are registering with root injector with this syntax { 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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