繁体   English   中英

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

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

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

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

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

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'
           })
       }
} 
}

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())
    }
} 

3) auth.module.ts

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


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

错误

垂钓者 9/10

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

只有两步:

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

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

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

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

你 2 种竞争注册服务的方法进行依赖注入,注册BaseService是无效的。

暂无
暂无

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

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