我的 Angular 應用程式(和相關部分)的結構如下:
應用程式/app.module.ts
import { DbService } from './db.service'
const APP_CONTAINERS = [
DefaultLayoutComponent,
DefaultHeaderComponent,
];
@NgModule({
declarations: [ ...APP_CONTAINERS ],
providers: [ DbService ]
})
export class AppModule {}
app/containers/default-layout.component.ts
import { Component, HostBinding, Inject } from '@angular/core';
import { DbService } from '../../db.service';
import { navItems } from './_nav';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
@Component({
selector: 'app-dashboard',
templateUrl: './default-layout.component.html'
})
export class DefaultLayoutComponent {
@HostBinding('class.c-app') cAppClass = true;
constructor(private DbService: DbService) {}
async ngOnInit() {
console.log('working')
}
}
我在網站的其他部分成功使用了相同的服務,但它們都有特定的 module.ts 檔案。我按照 Angular 教程到達我所在的位置,但無論我如何嘗試注入此服務,我仍然遇到錯誤。
我也嘗試在我的建構式中使用 @Inject 但收到相同的錯誤。
我目前在控制臺中收到以下錯誤:
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(e)[e -> e -> e -> e]:
NullInjectorError: No provider for e!
NullInjectorError: R3InjectorError(e)[e -> e -> e -> e]:
NullInjectorError: No provider for e!
uj5u.com熱心網友回復:
我在網站的其他部分成功使用了相同的服務,但它們都有特定的 module.ts 檔案
所以目前還不清楚你是如何劃分模塊的。從模塊檔案來看,它不像該組件在提供服務的模塊中那樣。該服務必須位于組件所在的注入樹的提供者中。如果該模塊檔案用于不同的模塊,則注入器必須知道您希望為服務提供什么。
一種解決方案是將它添加到您的組件的提供程式中。但是,這將獲得與其他模塊不同的服務實體:
@Component({
selector: 'app-dashboard',
templateUrl: './default-layout.component.html',
providers: [DbService]
})
export class DefaultLayoutComponent {
您也可以將它添加到您的組件所在模塊的提供程式中,但這也會獲得不同的實體。
我認為最好的方法是定義服務,以便它應該在根模塊中提供。這樣你就不必在任何地方的提供者中添加它,angular 會在需要時自動將它添加到根模塊的提供者中。這導致了屋大維在他的評論中所說的話。我認為您只是將此代碼錯誤地放在組件而不是服務中。將其移至服務并從providers模塊中的陣列中洗掉該服務:
@Injectable({
providedIn: 'root'
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345347.html
標籤:javascript 有角的 服务
