Can't resolve all parameters for UserProvider - Dependency Injection trouble


#1

I’ve read that @Inject should do the trick, and if not that I’ll need to use forwardRef, though I’m not quite sure how I would go about using this.
Any help would be greatly appreciated.

Error:
Can't resolve all parameters for UserProvider: (?, Http, Storage, Events).

UserProvider:

import { Injectable, Component, forwardRef, Inject } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';
import { CPService } from '../providers/CP';
import * as CryptoJS from 'crypto-js';
import { Events } from 'ionic-angular';

@Injectable()
export class UserProvider {
  public currentAccount: User;
  public accounts: UserList;

  constructor(@Inject(CPService) public cpService :CPService,
              public http: Http,
              public storage: Storage,
              public events: Events,
              ) {
    //stuff
}

CPService:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { CryptoService } from 'crypto-service';
import * as CryptoJS from 'crypto-js';
import * as QueryString from 'querystring';
import * as https from "https";
import { UserProvider } from '../providers/user';
import { Storage } from '@ionic/storage';
import { Headers, RequestOptions } from '@angular/http';

@Injectable()
export class CPService {
    constructor(public http: Http, public userProvider:UserProvider) {
        //stuff
    }
}

#2

I think you don’t need the @Inject(...) decorator here, but only the @Injectable(...). From the Angular 2 docs, it seems this is mostly used for non-class injection.

Just change the constructor of UserProvider:

constructor(public cpService :CPService,
              public http: Http, ...

And add the provider in app.module.ts like so:

providers: [
        { provide: ErrorHandler, useClass: IonicErrorHandler },
        UserProvider
    ]

#3

I removed the @Inject decorator, and added the provider in my app.module.ts, but I’m still getting the same error:
Can't resolve all parameters for UserProvider: (?, Http, Storage, Events).

@ntaso


#4

You are going to need forwardRef, unless you come up with some other way to break the circular dependency between UserProvider and CPService.