角度 6 将注射数组传递给 app.module.ts 中的提供程序导致:"Error in Cannot read property 'length' of undefined"



我有以下数组,其中包含从服务连接的可注射物

import { YouTubeSearchService,
YOUTUBE_API_KEY,
YOUTUBE_API_URL } from './you-tube.service';
export const youTubeSearchInjectables: Array<any> = [
{ provide: YouTubeSearchService, useClass: YouTubeSearchService },
{ provide: YOUTUBE_API_KEY, useClass: YOUTUBE_API_KEY },
{ provide: YOUTUBE_API_URL, useClass: YOUTUBE_API_URL }
];

我正在尝试将其传递给app.module.ts中的提供者:

/*other imports*/
import { youTubeSearchInjectables } from './search-result/you-tube-search.injectables';
@NgModule({
declarations: [
AppComponent,
SimpleHttpComponent,
SearchResultComponent,
SearchBoxComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [youTubeSearchInjectables],
bootstrap: [AppComponent]
})
export class AppModule { }

但是,我收到"无法读取未定义的属性'长度'中的错误">(只有一行,没有别的(。

我相信原因很可能与Angular的版本有关。我使用的是 6,书籍项目是用版本 5 编写的。然而,关于依赖注入的 Angular 文档说,书本方式是正确的方式......所以我有点困惑。或者也许我只是错过了一些东西。

我实际上尝试手动将每个可注射对象添加到 app.module 中,但遇到了相同的错误。

任何帮助将不胜感激

编辑:根据ng6更新尝试">提供:"root",但这没有帮助。

以防万一 - 可注射类:

/*imports*/
export const YOUTUBE_API_KEY = 'keykeykey';
export const YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/search';
@Injectable({
providedIn: 'root',
})
export class YouTubeSearchService {
constructor(
private http: HttpClient,
@Inject(YOUTUBE_API_KEY) private apiKey: string,
@Inject(YOUTUBE_API_URL) private apiUrl: string
) { }
search(query: string): Observable<SearchResult[]> {
// logic
}
}

我看到你的代码有两个问题。首先,您在数组中使用数组中的数组来定义提供程序。直接引用youTubeSearchInjectables变量,或使用 spread 运算符将导出的提供程序连接到模块的提供程序数组中。

第二个问题(在解决第一个问题之前您不会注意到(是您应该使用useValue而不是useClass来表示YOUTUBE_API_KEYYOUTUBE_API_URL,因为这两个不是类而是简单的字符串值。

const youTubeSearchInjectables: Array<any> = [
{ provide: YouTubeSearchService, useClass: YouTubeSearchService },
{ provide: YOUTUBE_API_KEY, useValue: YOUTUBE_API_KEY },
{ provide: YOUTUBE_API_URL, useValue: YOUTUBE_API_URL }
];
@NgModule({
providers: [
...youTubeSearchInjectables
],
bootstrap: [AppComponent]
})
export class AppModule { }

相关内容

最新更新