What is the proper way to inject a service in Angular 8?

angular inject service without constructor
angular 8 service example
dependency injection in angular 7
angular inject service into service
angular service constructor parameters
angular constructor parameters
angular inject interface
angular injection token

I am trying to inject a service to my main "App" component. But it gives an error(Screenshot attached Below)

constructor(private newsApi: NewsApiService) {}

When importing service with the above code I get this error

I googled and found the solution. Which is adding

@Inject

constructor(@Inject(NewsApiService) newsApi: NewsApiService) {}

But in the documentation of Angular.io, it shows the first way that I used. I want to know if I am missing something here?

My NewsApiService has HttpClient and it sends HTTP request. Functions written in this service are all Async as they need to send a request and get data.

NewsApiService.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class NewsApiService {
  apiKey = '--My_API_Key_Goes_here--';

  constructor(private http: HttpClient) {
  }

  initSources() {
    return this.http.get('https://newsapi.org/v2/sources?language=en&apiKey=' + this.apiKey);
  }

  initArticles() {
    return this.http.get('https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=' + this.apiKey);
  }

  getArticlesByID(source: string) {
    return this.http.get('https://newsapi.org/v2/top-headlines?sources=' + source + '&apiKey=' + this.apiKey);
  }
}

App.module.ts Added the service in provider to access everywhere

providers: [NewsApiService],

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {
  MatButtonModule,
  MatCardModule,
  MatIconModule,
  MatListModule,
  MatMenuModule,
  MatSidenavModule,
  MatToolbarModule
} from '@angular/material';

import { AppComponent } from './app.component';
import {NewsApiService} from './news-api.service';
import {FormsModule} from '@angular/forms';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    BrowserAnimationsModule,
    HttpClientModule,
    MatButtonModule,
    MatMenuModule,
    MatCardModule,
    MatToolbarModule,
    MatIconModule,
    MatSidenavModule,
    MatListModule,
  ],
  providers: [NewsApiService],
  bootstrap: [AppComponent]
})
export class AppModule { }

App.component.ts

import {Component, Inject, OnInit} from '@angular/core';
import {NewsApiService} from './news-api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent{
  mArticles: Array<any>;
  mSources: Array<any>;

  constructor(@Inject(NewsApiService) newsApi: NewsApiService) {}
}

Sometimes you have to restart ng serve for it to pick up changes in new files. I experience this occasionally with injector dependencies where I add a new code file that serves as a dependency in another component/service.

Introduction to services and dependency injection, You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances. Angular  How to inject a service. There are a couple of ways to inject an Angular services. Angular Injector. You can import Injector from ‘@angular/core’ and use this injector object to inject / get a service by its token. Using injector allows more control on when and whether to inject a service. However, greater flexibility comes with a cost. When you use an injector to inject a service and if the service is not used, it is not tree-shakable. This is because Angular compiler cannot identiy all

If you want to use the injection explicitly vs Injectable, please have a look at the already answered post:

What is the difference between @Inject and @Injectable in Angular 2 typescript

Dependency injection in Angular, The consumer of an injected service doesn't need to know how to create that injection framework resolves these nested dependencies in the correct order. We can inject the Angular Service in Application Level or Module Level. The provider's property of NgModule decorator gives us the ability to inject a list number of Angular services into the module level. It will provide a single instance of the Angular Service across the entire application and can share the same value within different components.

Use @Injectable() Decorator which enables a class to be injected to a particular class or component.

Basically the following three steps makes service consumption

1.) Decorate the service with @Injectable() like @Injectable() export class SampleService{ constructor(){ } }

2.) Add the service reference in the providers array of @NgModule Decorator of module file.

3.)// Consume the service constructor(private sampleService: SampleService) {}

As far as I see your screenshot, it is not a staticInjector error which is thrown in case of injection issue.

Dependency injection in action, How to Implement Services and Dependency Injection in Angular 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { Component, OnInit, OnDestroy } we can see the earlier message being logged properly, that proves that we  @Inject The @Inject () is a constructor parameter decorator, which tells angular to Inject the parameter with the dependency provided in the given token. It is a manual way of injecting the dependency In the previous example, when we removed the @Injectable decorator from the ProductService we got an error.

How to Implement Services and Dependency Injection in Angular , An Angular service is simply a TypeScript class that encapsulates the various methods for completing a certain task in your app such as getting  Thanks to injector inheritance, you can still inject application-wide services into these components. A component's injector is a child of its parent component's injector, and inherits from all ancestor injectors all the way back to the application's root injector. Angular can inject a service provided by any injector in that lineage.

Angular 9/8 Services & Dependency Injection via providedIn, root , Step 3 — Importing and Injecting HttpClient. Open the src/app/backend.service.ts file, then import and inject HttpClient as follows: import  After setting up HttpClient in your project, you need to create a service which will import HttpClient and use it to send any HTTP requests needed in your application. This service will be then injected in any component that needs to do any HTTP operations. Go to your terminal and start by generating a service using the Angular CLI 8:

How to Create a Service with HttpClient and Injectable in Angular 9/8, There are simply two steps for creating services in Angular: In Angular Framework, Service injection is one way of performing dependency  In order to migrate an Angular 5 project to Angular 8, I've created an empty project with Angular CLI and copied my modules, components and services in my new project structure. The project builds, but at the execution I've got the classic message "No provider for HttpClient in service" :

Comments
  • Please show the contents of app.module.ts
  • If you use providedIn: 'root', you do not need to add this service to the providers array. Are you importing HttpClientModule in app.module.ts? If you are, your code should be working stackblitz.com/edit/angular-d9xt1b
  • I edited and added my app.module.ts file too
  • Have you tried killing the ng serve process and restarting it? I don't see any reason why your code should not work without @Inject
  • No worries, it does not matter now anyways as you found the answer. This is something I have to do every once in a while as well when adding new code files.