Sunday, January 14, 2018

StaticInjectorError NullInjectorError: No provider for MyService


Hi Guys,

You might have faced an error like "StaticInjectorError NullInjectorError: No provider for MyService".

This error comes when you try to create a service and something goes wrong.

Let's see the full stack trace.

ERROR Error: StaticInjectorError[MyService]: 
  StaticInjectorError[MyService]: 
    NullInjectorError: No provider for MyService!
    at _NullInjector.get (webpack-internal:///../../../core/esm5/core.js:1189)
    at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477)
    at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419)
    at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290)
    at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477)
    at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419)
    at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290)
    at resolveNgModuleDep (webpack-internal:///../../../core/esm5/core.js:11074)
    at NgModuleRef_.get (webpack-internal:///../../../core/esm5/core.js:12306)
    at resolveDep (webpack-internal:///../../../core/esm5/core.js:12804)


I have few tips which will help you Debug this.


Let's see the working code
import { Component, OnInit } from '@angular/core';
import { MyService } from './myapp.service';


@Component({
  selector: 'app-question',
  templateUrl: './myapp.component.html',
  styleUrls: ['./myapp.component.css'],
  providers:[MyService ]
})
export class MyComponent implements OnInit {

  constructor(private myService:MyService ) { }
  //constructor() { }
  ngOnInit() {

this.data=this.myService.loadData();
console.log(data);
  }
var data={};

}
In the above code I have successfully created a service .You need to check if you have specified the service in providers.If you have not added ,add it in the provider attribute of @Component decorator .

Apart from this you need to add the service to app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { MyService } from './myapp.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [MyService],
  bootstrap: [AppComponent]
})
export class AppModule { }

No comments:

Post a Comment

ec2-user@ec2 Permission denied