angular 9 dependency injection error. " The class cannot be created via dependency injection, as it does not have an Angular decorator

Viewed 12429

The same code worked for me in angular 8 but now it's giving me this error. "The class 'BaseService' cannot be created via dependency injection, as it does not have an Angular decorator. This will result in an error at runtime.

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

I'm only trying to achieve simple inheritence here.

1) BaseService.ts (parent class)

import { environment } from 'src/environments/environment';
import { HttpHeaders } from '@angular/common/http';

export class BaseService {
    url
    constructor(postfixUrl) {
        this.url = environment.backendUrl + postfixUrl
    }

    setUpHeaders() {
       return {
           headers: new HttpHeaders({
               'Content-Type': 'application/json'
           })
       }
} 
}

2) AuthService.ts (child class)

import { Injectable } from "@angular/core";
import {HttpClient} from '@angular/common/http'
import { BaseService } from './base.service';

@Injectable({
    providedIn: 'root'
  })

export class AuthService extends BaseService {
    url
    constructor(private http: HttpClient) {
        super('auth')
    }
    register(user) {
        return this.http.post(this.url, user, this.setUpHeaders())
    }
} 

3) auth.module.ts

@NgModule({
  declarations: [
    AuthComponent,
    LoginComponent,
    RegisterComponent
  ],
  imports: [
    CommonModule,
    AuthRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule


  ],
  providers: [AuthService, BaseService]
})
export class AuthModule { }

the error

2 Answers

If you want to use a service for a single module then you do not need to use @Injectable({ providedIn: 'root' }).

Two steps:

  1. @Injectable() add in your service.
  2. providers: [ BaseService ] add in your module inner NgModule.

You have added BaseService to the module providers. BaseService accepts the parameter postfixUrl in its constructor.

You should remove at least the BaseService from the providers, since Angular won't know how to resolve the parameters.

Adding a service to the module providers means that an instance of that service will be shared within that module. Adding @Injectable({ providedIn: 'root' }) means it will be shared within the whole app.

You 2 competing methods of registering services for dependency injection, and registering BaseService is invalid.

Related