Bryan
Bryan

Reputation: 3009

cyclic dependency error when importing service into another service

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:

Unhandled Promise rejection: Provider parse errors: Cannot instantiate cyclic dependency! Http: in NgModule AppModule in ./AppModule ; Zone: ; Task: Promise.then ; Value:

Here is my default-request-options.service.ts file:

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 };

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 ]
})

What am I doing wrong?

Upvotes: 1

Views: 948

Answers (1)

danday74
danday74

Reputation: 57046

Imagine 3 services ..

Service1, Service2, Service3

  • Service1 imports Service2
  • Service2 imports Service3
  • Service3 imports Service1

Service1 tries to import 2, 2 tries to import 3, 3 tries to import 1 and this continues forever. This is a cyclic dependency.

Break the loop to fix it.

Upvotes: 1

Related Questions