Dependency injection, Angular

Asked

Viewed 179 times

0

I’m learning Angular, and I’ve had a little bit of addiction injections. On the site it says that the @Injectable() decorator must have a declared service provider. Something like this:

@Injectable({ providedIn: 'root', }) But when I put it the IDE accuses error, saying that the decorator expects 0 arguments and has a gift, and the project does not work. How do I fix this?

  • Maybe you didn’t declare it as Provider in the app.module

1 answer

1

Just put

@Injectable() 
export class MeuService 

and put the service inside the providers in app.module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { JokeModule } from './joke/joke.module';
import { MeuService } from './meuService.service';

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

Putting the service in the app module it will be a Singleton for the entire application that in most cases and the desired behavior.

Browser other questions tagged

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