【问题标题】:cyclic dependency error when importing service into another service将服务导入另一个服务时出现循环依赖错误
【发布时间】:2017-02-17 21:26:41
【问题描述】:

我正在尝试使用 Angular 2 提供的 DefaultRequestOptions 类为我的 http 请求设置默认标头。可以在此处找到文档:https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options

我想添加一个默认不记名令牌,该令牌在我的一项服务中设置,但这样做会在我的浏览器控制台中出现以下错误:

未处理的 Promise 拒绝:提供程序解析错误:无法实例化 循环依赖! http:在 NgModule AppModule 中的 ./AppModule ;区: ;任务:Promise.then;价值:

这是我的 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 文件中的相关代码:

import { requestOptionsProvider }         from './default-request-options.service';
import { UserService }                    from './user.service';

@NgModule({ 
    imports: [
        ...
    ],  
    declarations: [
        ...
    ],    
    providers: [        
        ...        
        requestOptionsProvider,        
        UserService
    ],
    bootstrap: [ AppComponent ]
})

我做错了什么?

【问题讨论】:

标签: angular angular2-services angular2-http


【解决方案1】:

想象 3 种服务 ..

服务1、服务2、服务3

  • Service1 导入 Service2
  • Service2 导入 Service3
  • Service3 导入 Service1

Service1 尝试导入 2,2 尝试导入 3,3 尝试导入 1,这将永远持续下去。这是一个循环依赖。

打破循环以修复它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2021-08-15
    • 2016-08-07
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多