Injecting a custom service without having to pass it in the constructor


#1

Hi, I am trying to inject my own service, CommonUtils into another file. Lets call that other file Boris , without passing an instance in the constructor, but it isn’t working. I don’t see any error either, so I’m not sure what is going on.

This is the code in Boris

import {ReflectiveInjector} from '@angular/core';
import { CommonUtilsProvider } from '../providers/common-utils/common-utils';

// 

export class Boris {

constructor (public items: any[]){
        this.items = items;
        this.mRec = Observable.create(observer => { 
            this.mRec.Observer = observer;
        });

    } 
// I need access to a CommonUtils function in this method
removeItem(item):void {
    let injector = ReflectiveInjector.resolveAndCreate([CommonUtilsProvider]);
        let commonUtils = injector.get(CommonUtilsProvider);
        commonUtils.someFunction() ;

This is how CommonUtilsProvider is defined

@Injectable()
export class CommonUtilsProvider {
  constructor(private toastCtrl: ToastController, private camera: Camera, private transfer: Transfer, private file: File, private filePath: FilePath) {
    console.log('Hello CommonUtilsProvider Provider');
  }

I’m successfully using CommonUtilsProvider in many other places using the traditional constructor based approach, but I can’t do that in this file because I don’t want to add another parameter Boris’ constructor.


#2

Okay, problem identified. these errors don’t show up when looking at Xcode (iOS). They did come up when running in the browser - looks like I need to inject a whole bunch of dependencies - don’t like this route. I’ll look for another solution.