15

I have two services: LoginService and UserService. I am trying to inject UserService into LoginService and the app won't run.

In the console, I have the error:

Error: Can't resolve all parameters for UserService: ([object Object], ?). at SyntaxError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:7156:33) at SyntaxError.BaseError [as constructor]

this is my LoginService:

import {UserService} from '../services/user.service';
@Injectable()
export class LoginService {

  constructor(public _http: Http,public us:UserService) {
  }

and UserService:

 @Injectable()
    export class UserService {
    constructor(private _http: Http , public _ls: LoginService) {

    }

angular module:

import {LoginService} from './services/login.service';
import {UserService} from './services/user.service';

@NgModule({
  declarations: [
    AppComponent,


  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserService, LoginService, appRoutingProviders],
  bootstrap: [AppComponent]
})
export class AppModule { }
nephiw
  • 1,964
  • 18
  • 38
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43

2 Answers2

30

You have a circular reference.

Your UserService requires LoginService, and LoginService requires UserService.

Remove one of the dependencies. E.g. refactor your UserService so that it does not require a reference to LoginService

Liam George Betsworth
  • 18,373
  • 5
  • 39
  • 42
Steve Land
  • 4,852
  • 2
  • 17
  • 36
3

As the other posted mentioned a circular dependency... you may consider using forwardRef() to resolve this issue.

In a nutshell, we can inject a Forward Reference instead of the real service. So the service injection will be deferred. Thus the circular dependency is solved.

Here is a code sample:

import {Component, Inject, forwardRef} from '@angular/core';

@Component({
  selector: 'my-app',
  template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
  name: string;

  constructor(@Inject(forwardRef(() => NameService)) nameService) {
    this.name = nameService.getName();
  }
}

class NameService {
  getName () {
    return "Angular";
  }
}

You can check this page for further details.

Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
  • Can you include the necessary parts of the forum post in your question? It is always recommended to include the actual answer rather than referring with a link – Ibo Oct 05 '17 at 21:14
  • I think it should be something more like this: `constructor(@Inject(forwardRef(() => NameService)) nameService: NameService) { this.name = nameService.getName(); }` – Robert Feb 27 '18 at 12:44