Nullinjector error: No Provider for

Asked

Viewed 16,831 times

5

I’m getting this error message:

ERROR Error: StaticInjectorError[CervejaService]: 
  StaticInjectorError[CervejaService]: 
    NullInjectorError: No provider for CervejaService!
    at _NullInjector.get (core.js:993)
    at resolveToken (core.js:1281)
    at tryResolveToken (core.js:1223)
    at StaticInjector.get (core.js:1094)
    at resolveToken (core.js:1281)
    at tryResolveToken (core.js:1223)
    at StaticInjector.get (core.js:1094)
    at resolveNgModuleDep (core.js:10878)
    at NgModuleRef_.get (core.js:12110)
    at resolveDep (core.js:12608)

And I’m sure it’s because of that line of code:

import { Cerveja } from './../core/model';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class CervejaService {

  cervejasUrl = 'http://localhost:8080/cervejas';

  constructor(private http: Http) { }

  adicionar(cerveja: Cerveja): Promise<Cerveja> {
        return this.http.post(this.cervejasUrl,
        JSON.stringify(cerveja))
      .toPromise()
      .then(response =>  response.json());
  }
}

How do I know what’s coming back? Would have some way to apply in that method a console.log?

2 answers

14


You need to add your CervejaService on the list of providers of your module.

Example:

import { CervejaService } from './cerveja.service';

@NgModule({
  imports: [
    // ...
  ],
  declarations: [
    // ...
  ],
  providers: [
    CervejaService, // seu provider aqui
  ]
})

2

Or if you don’t want to put in all the models that need services you can always do:

import { Cerveja } from './../core/model';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable({
  providedIn: 'root', // <---- Adiciona isto ao serviço
})
export class CervejaService {

  cervejasUrl = 'http://localhost:8080/cervejas';

  constructor(private http: Http) { }

  adicionar(cerveja: Cerveja): Promise<Cerveja> {
        return this.http.post(this.cervejasUrl,
        JSON.stringify(cerveja))
      .toPromise()
      .then(response =>  response.json());
  }
}

By doing this, you don’t need to add to module the service

I hope it helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.