Angular 2 can't resolve all parameters for service

Mohammed Yassine CHABLI picture Mohammed Yassine CHABLI · Jun 5, 2017 · Viewed 20.8k times · Source

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

Answer

Steve Land picture Steve Land · Jun 5, 2017

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