简体   繁体   中英

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

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

Anguler 9/10

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

Only two step:

  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.

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