Help! I keep getting the NullInjectorError in the console saying there is no provider for Subscription. Why is this happening?

Here is the code snippet I'm working on within a component:


import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {
  constructor(private firstObsSubscription: Subscription) {}

  ngOnInit() {
    interval(1000).subscribe((count) => console.log(count));
  }

  ngOnDestroy() {
    this.firstObsSubscription.unsubscribe();
  }
}

After defining the component, it gets included in a module and later gets injected into another module.


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

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { UserComponent } from './user/user.component';
import { AppRoutingModule } from './app-routing.module';

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

It seems like something is not quite right with my code implementation

Answer №1

If you're looking to accomplish a specific task, consider the following approach:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {

  private firstObsSubscription: Subscription
  
  constructor() {}

  ngOnInit() {
    this.firstObsSubscription = interval(1000).subscribe((count) => console.log(count));
  }

  ngOnDestroy() {
    this.firstObsSubscription?.unsubscribe();
  }
}

It has been noted in the comments by others: When adding a parameter to a constructor in an Angular Application, Angular will attempt to find a dependency of that type which may not be present or necessary in your current scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 16 throwing a NullInjectorError within an interceptor

Currently, I am working on setting up a new interceptor within an Angular 16 project. However, when attempting to inject MatSnackBar into the project, I encounter the following error message: NullInjectorError: NullInjectorError: No provider for MatSnack ...

Unable to access property '_lastPathIndex' of an undefined value

In my component spec, I am simulating the Activated Route like this: class ActivatedRouteMock { public paramMap = of(convertToParamMap({ level: 'customer', id: '12345', })); } I have also added this class in the providers ...

Learn the process of sending a delete request to a REST API with Angular

Is there a way to effectively send a delete request to a REST API using Angular? I am attempting to send a delete request with an ID of 1 My current approach is as follows: this.http.delete(environment.apiUrl+"id="+1).subscribe(data => { }); The va ...

Tips for Mastering Animation Anchoring with Angular 2

Did you know that AngularJS 1.4 has a unique animation feature called Animation Anchoring? This feature allows you to mark elements in both the source and destination pages with the attribute ng-animate-ref, creating a computed animation between the two b ...

Adding Images Using Angular 8

I'm encountering difficulties with image upload in the file located at '../src/app/assets/'. Below is the Form I am using: <form [formGroup]="formRegister" novalidate=""> <div class="form-group"> <label for="ex ...

The alertController will only appear on the original page where it was first activated

I am facing a peculiar issue with the alertController in my Ionic application. Let me explain the problem and then provide the relevant code snippets. In my Ionic app with tabs, I encounter an issue where alerts are not showing up correctly. For example, ...

Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreePreArray ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

Encountering build errors with @angular/cdk and @angular/forms post updating to Angular 11

Upon upgrading to Angular 11, I encountered a series of errors during the build process of my solution: \node_modules\@angular\cdk\coercion\array.d.ts(10,60): error TS1005: Build:',' expected. \node_modules\@ang ...

Update the mandatory fields in the required interface to extend to another interface, while ensuring that all subfields become

Currently, I have defined 2 interfaces: interface BattleSkills { strength: number; armor: number; magic_resistance: number; health: number; mana: number; intelligence: number; accuracy: number; agility: number; critical_damage: number; } ...

ASP.NET 5 controller's action not binding correctly with Angular2 Http post request

When sending a post request from Angular2 to an ASP.NET 5 controller action, although the data is being posted correctly and the controller action is being reached, the parameters defined in the controller action are not being properly mapped as they are s ...

Integrating d3.js into an Angular 2 project

Trying to incorporate the d3.js library into a MEAN application using angular2. Here are the steps I've taken: npm install d3 tsd install d3 In mypage.ts file (where I intend to show the d3.js graph) // <reference path="../../../typings/d3/d3.d ...

What is the best way to restrict the suggested values in a property depending on the value of another property?

I'm working on creating a third interface that depends on the value of properties from two other interfaces, while also introducing a unique third property. I've chosen not to extend the third property from the first two interfaces as it may not ...

Dividing component files using TypeScript

Our team has embarked on a new project using Vue 3 for the front end. We have opted to incorporate TypeScript and are interested in implementing a file-separation approach. While researching, we came across this article in the documentation which provides ...

The module 'atptest' could not be located or its corresponding type declarations are missing. Error code: ts(2307)

After creating an angular library using angular cli, I encountered an issue when trying to use it in any angular application after publishing it to npm. The published library installs successfully with the command: npm i atptest This is how I attempted t ...

Encountering an issue while attempting to incorporate an interface within a class in TypeScript

Can someone please help me figure out what I'm doing wrong? I'm attempting to implement an interface inside a class and initialize it, but I keep encountering this error: Uncaught TypeError: Cannot set property 'name' of undefined at n ...

The numerical value of zero in React Native TypeScript is being interpreted as NaN

When attempting to map an array in React Native (Android) and use its values or keys as data for return, I encountered an issue where the value 0 is read as NaN. This problem also arose when utilizing a typescript enum. The versions I am using are: typesc ...

Best location for Angular PWA update handler?

Running a PWA app led me to think about decluttering the application.component. To achieve this, I created a dedicated service to monitor PWA updates and alert the user: import { Injectable } from '@angular/core'; import { MatSnackBar } from &qu ...

A guide on transitioning from using require imports to implementing ES6 imports with the concept of currying

Currently in the process of migrating a Node/Express server to TypeScript. I have been using currying to minimize import statements, but now want to switch to ES6 import syntax. How can I translate these imports to ES6? const app = require("express")(); ...

Angular threw an error stating that it encountered an unexpected token 'var' when trying to declare a variable x as

Currently facing a challenge with my Angular application development. I have created a TS File that interacts with my API (imported in the index.html using a script tag) and exported some functions from this file to be used in my components. Despite everyt ...