angular 9 依赖注入错误。" 该类不能通过依赖注入创建,因为它没有 Angular 装饰器

A R*_*A R 3 angular

相同的代码在 angular 8 中对我有用,但现在它给了我这个错误。“无法通过依赖注入创建类 'BaseService',因为它没有 Angular 装饰器。这将导致运行时出错。

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

我只是想在这里实现简单的继承。

1)BaseService.ts(父类)

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'
           })
       }
} 
}
Run Code Online (Sandbox Code Playgroud)

2)AuthService.ts(子类)

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())
    }
} 
Run Code Online (Sandbox Code Playgroud)

3) auth.module.ts

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


  ],
  providers: [AuthService, BaseService]
})
export class AuthModule { }
Run Code Online (Sandbox Code Playgroud)

错误

MD *_*hik 5

垂钓者 9/10

如果要为单个模块使用服务,则不需要使用@Injectable({ providedIn: 'root' }).

只需两步:

  1. @Injectable() 添加您的服务。
  2. providers: [ BaseService ]在你的模块内添加NgModule


Kur*_*ton 1

您已添加BaseService到模块提供程序。BaseService接受其构造函数中的参数postfixUrl

您应该至少BaseService从提供者中删除 ,因为 Angular 不知道如何解析参数。

将服务添加到模块提供程序意味着该服务的实例将在该模块内共享。添加@Injectable({ providedIn: 'root' })意味着它将在整个应用程序内共享。

您使用两种相互竞争的方法来注册依赖注入服务,并且注册BaseService无效。