'inject() must be called from an injection context' when importing services between Angular and Ionic project

219 Views Asked by At

I am trying to create a "simplest possible" mechanism for sharing code between an Angular web project & Ionic/Angular mobile app. I have also been exploring a monorepo approach, but thought I would see if it was possible to simply import modules that live in the web project from the mobile project.

This seems to work perfectly between multiple Angular projects, but when I import a service ( which itself makes use of another service) into the Ionic project, I get the runtime error: 'inject() must be called from an injection context'.

I was wondering whether this is a solvable problem, or is it something which just isn't supposed to work?

I can demonstrate this with a minimal pair of freshly-installed projects using Angular 10.0.5, and Ionic 6.11.0 which itself installs Angular 9.1.6.

I have tried some suggestions I have found through searches:

  • Setting preserveSymlinks to true in the angular.json
  • Setting "paths": { "@angular/": [ "./node_modules/@angular/" ] } in the tsconfig.json

I have also tried some different ways of providing the Service in the importing app:

  • providedIn: root
  • class in the list of providers in the app.module.ts
  • explicit providers in the form [MyOtherService, { provide: MyService, useClass: MyService }]

EDIT: To demonstrate the problem I created 2 very basic dummy services in the Angular project where one references the the other:

DummyService.ts

import {Injectable} from '@angular/core';
import {Dummy2Service} from './dummy2.service';

@Injectable({
  providedIn: 'root'
})
export class DummyService {

  constructor(private d2Service: Dummy2Service) {}

  get str() {return "Service 1";}

  get str2() {return this.d2Service.str;}
}

Dummy2Service

import {Injectable} from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class Dummy2Service {

  constructor() {}

  get str() {return "Service 2";}
}

Then in the Ionic project all you need to do to cause the error is reference the one dummy service (from the other project) in the app component:

// import references a service in another project
import {DummyService} from '../../../my-app2/src/app/dummy.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private dummyService: DummyService) {
  }
}
0

There are 0 best solutions below