簡體   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