nativescript-schematics icon indicating copy to clipboard operation
nativescript-schematics copied to clipboard

NullInjectorError when importing shared service

Open Mitko-Kerezov opened this issue 6 years ago • 1 comments

Suppose I have my-service.tns and my-service.tns.ts and I have core.module.ts and core.module.tns.ts respectively.

In core.module.ts I have:

import { NgModule, NO_ERRORS_SCHEMA, ModuleWithProviders } from '@angular/core';
import { NativeScriptRouterModule } from 'nativescript-angular/router';
import { NativeScriptUISideDrawerModule } from 'nativescript-ui-sidedrawer/angular';

import { MyService } from './my-service';

@NgModule({
  imports: [NativeScriptRouterModule, NativeScriptUISideDrawerModule],
  exports: [NativeScriptRouterModule, NativeScriptUISideDrawerModule],
  schemas: [NO_ERRORS_SCHEMA],
})
export class CoreModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [
        MyService
      ]
    };
  }
}

In core.module.tns.ts I have the exact same contents except instead of

import { MyService } from './my-service';

I have

import { MyService } from './my-service.tns';

Now suppose I have my-file.ts file which is shared for web and mobile where I want to make use of this service:

import { MyService } from './my-service';

@Injectable()
export abstract class MyFile {
     constructor(protected myService: MyService) { }
}

However this fails during runtime (tns run --bundle) with:

JS:     NullInjectorError: No provider for MyService!
JS: Error: NullInjectorError: No provider for MyService!
JS:     at NullInjector.push.../node_modules/@angular/core/fesm5/core.js.NullInjector.get (file:///data/data/org.nativescript.nsshared/files/app/vendor.js:32171:19) [angular]
JS:     at resolveToken (file:///data/data/org.nativescript.nsshared/files/app/vendor.js:32409:24) [angular]
JS:     at tryResolveToken (file:///data/data/org.nativescript.nsshared/files/app/vendor.js:32353:16) [angular]
JS:     at StaticInjector.push.../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (file:///data/data/org.nativescript.nsshared/files/app/vendor.js:32250:20) [angular]
JS:     at resolveToken (file:///data/data/org.nativescript.nsshared/files/app/vendor.js:32409:24) [angular]
JS:     at tryResolveToke...

Mitko-Kerezov avatar Jan 15 '19 14:01 Mitko-Kerezov

On a side note

When I remove the tns extension from the import

import { MyService } from './my-service.tns';

inside core.module.tns.ts everything works as expected - no crash at runtime.

Mitko-Kerezov avatar Jan 15 '19 14:01 Mitko-Kerezov