将服务导入另一个服务时出现循环依赖错误 [英] cyclic dependency error when importing service into another service
问题描述
我正在尝试使用 Angular 2 提供的 DefaultRequestOptions 类为我的 http 请求设置默认标头.可以在此处找到文档:https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-默认请求选项
I'm trying to set default headers for my http requests using the DefaultRequestOptions class provided by Angular 2. Documentation can be found here: https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options
我想添加一个默认的不记名令牌,该令牌设置在我的一项服务中,但这样做会在我的浏览器控制台中出现以下错误:
I want to add a default bearer token, which gets set in one of my services, but doing so gives me the following error in my browser console:
未处理的承诺拒绝:提供程序解析错误:无法实例化循环依赖!http: 在 NgModule AppModule 中的 ./AppModule ;区:;任务:Promise.then;价值:
Unhandled Promise rejection: Provider parse errors: Cannot instantiate cyclic dependency! Http: in NgModule AppModule in ./AppModule ; Zone: ; Task: Promise.then ; Value:
这是我的 default-request-options.service.ts 文件:
import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions } from '@angular/http';
import { UserService } from './user.service';
@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {
constructor(private userService: UserService) {
super();
// Set the default 'Content-Type' header
this.headers.set('Content-Type', 'application/json');
this.headers.set('Accept', 'application/json');
this.headers.set('Authorization', 'Bearer ' + this.userService.idToken);
}
}
export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };
这是我的app.module.ts文件中的相关代码:
Here is the relevant code in my app.module.ts file:
import { requestOptionsProvider } from './default-request-options.service';
import { UserService } from './user.service';
@NgModule({
imports: [
...
],
declarations: [
...
],
providers: [
...
requestOptionsProvider,
UserService
],
bootstrap: [ AppComponent ]
})
我做错了什么?
推荐答案
Imagine 3 services ..
Imagine 3 services ..
服务 1、服务 2、服务 3
Service1, Service2, Service3
- Service1 导入 Service2
- Service2 导入 Service3
- Service3 导入 Service1
Service1 尝试导入 2,2 尝试导入 3,3 尝试导入 1,这将永远持续下去.这是一个循环依赖.
Service1 tries to import 2, 2 tries to import 3, 3 tries to import 1 and this continues forever. This is a cyclic dependency.
打破循环来修复它.
这篇关于将服务导入另一个服务时出现循环依赖错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!