Angular Error : StaticInjectorError (Platform: cor

2020-04-13 04:05发布

问题:

As I am build the APK with --prod I am getting the error below

    ERROR Error: StaticInjectorError[e -> t]: 
  StaticInjectorError(Platform: core)[e -> t]: 
    NullInjectorError: No provider for t!
    at e.get (core.js.pre-build-optimizer.js:8894)
    at core.js.pre-build-optimizer.js:9139
    at e (core.js.pre-build-optimizer.js:9083)
    at e.get (core.js.pre-build-optimizer.js:8980)
    at core.js.pre-build-optimizer.js:9139
    at e (core.js.pre-build-optimizer.js:9083)
    at e.get (core.js.pre-build-optimizer.js:8980)
    at Ua (core.js.pre-build-optimizer.js:21119)
    at e.get (core.js.pre-build-optimizer.js:21808)
    at Ts (core.js.pre-build-optimizer.js:22179)

But it working fine with Ionic Cordova build android also it working with ng serve; but I am getting the same above error with ng serve --prod".

How can I resolve this?

回答1:

You are trying to use a service that is not listed in providers of your AppModule or inside you component.ts. Add the service to a providers list to make it work.

In app.modules if you want that service to be global (related to app context).

@NgModule({
    declarations: [...],
    imports: [...],
    bootstrap: [...],
    entryComponents: [...],
    providers: [
        MyService
    ]
})

Or in your component.ts if you want that service to be contextual to desired component.

@Component({
    selector: '...',
    templateUrl: '...',
    providers: [MyService]
})

Do not add it in both files. Also don't forget to import that service when you inject it either in app.modules or component.

import { MyService } from '../services/myservice';

This question also may help you: Error: No provider for t



回答2:

This happens because you did not add the services used to build the module

example:

1. component

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {

constructor(private localServiceName: YourService) {
}

  ngOnInit() {
  }

}

2. module

@NgModule({
    declarations: [SampleComponent]
})

change to

@NgModule({
    declarations: [SampleComponent]
    providers: [ YourService ]
})