Angular 2 can't resolve all parameters for service

Viewed 21445

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 { }
2 Answers

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.

Related