Issue with Angular and rxjs: Subscription provider not found

Trying to establish communication between a service and component in Angular, where the service holds a value and the component subscribes to its changes. Currently utilizing rxjs Subscription, but encountering an issue:

Uncaught (in promise): Error: No provider for Subscription!

This is what's implemented in the service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class PracticeContextService {
  practice: Subject<any> = new Subject<any>();
  public practiceSelected$ = this.practice.asObservable();

 setPractice(providerId: string) {
   this.practice.next({ providerId: providerId });
 }

 getPractice(): Observable<any> {
   return this.practice.asObservable();
 }
}

And here's how it's handled in the component:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { PracticeContextService } from '../practice-context.service';

@Component({
  selector : 'practice-context-selector',
  templateUrl : './practice-context-selector.component.html',
  styleUrls : ['./practice-context-selector.component.css']
})

export class PracticeContextSelectorComponent implements OnInit, OnDestroy {

  practice: string;

  constructor(private context: PracticeContextService,
          private subscription: Subscription) {}

  ngOnInit() {
    this.subscription = this.context.practiceSelected$.subscribe(
      practice => {
        this.practice = practice;
      });
  }

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

The component and service are then bundled into a module, which is subsequently injected into another module.

import { NgModule }           from '@angular/core';
import { CommonModule }       from '@angular/common';

import { PracticeContextSelectorComponent } from './practice-context-selector/practice-context-selector.component';
import { PracticeContextService } from './practice-context.service';

@NgModule({
  imports : [
    CommonModule
  ],
  declarations : [
    PracticeContextSelectorComponent
  ],
  providers : [
    PracticeContextService,
  ],
  exports: [
    PracticeContextSelectorComponent
  ]
})

export class PracticeContextModule {}

Somewhere along the way, a mistake seems to have been made.

Answer №1

To streamline the constructor, consider removing

private subscription: Subscription
and instead adding it as a class attribute.

Answer №2

One way to improve your code is by modifying the way you import rxjs dependencies. Instead of importing { Observable } from 'rxjs/Observable', it's recommended to do it as shown below:

import { Observable, Subscription } from 'rxjs/Rx';

I had encountered issues before when using a different import statement, so I now pay extra attention to this during development! Maybe there's more under the hood that I should explore further.

Additionally, following Lyubimov Roman's advice, avoid importing rxjs subscription through the constructor. It wasn't clear in your response to their comment, so providing examples could help us understand better what you meant.

When needing to use a subscription object in your component, simply import it like this:

import { Subscription } from 'rxjs/Rx';

Answer №3

Moving it outside of the constructor would be a better approach.

private _Subscription: Subscription;

  constructor() {
  }

Answer №4

When I first started working with angular, I encountered this issue multiple times and couldn't figure out what was causing it. One important thing to check is whether you have properly imported the necessary dependencies like

import { Observable, Subscription } from 'rxjs';

The error I kept running into was the dreaded Null Injection Error: No Provider for Subscription.

At first, I made the mistake of declaring the Subscription inside the constructor like this:

constructor(){private activatedsubscription:Subscription}

However, I learned that the reason for the Null Injection error was because the Subscription should be declared outside the constructor as a property or at a global level within the Class:

export class Component implements OnInit{
activatedsubscription:Subscription
}

Remember: Always remember to unsubscribe from the Subscription when destroying the Component by implementing the OnDestroy method. This will prevent any potential memory leaks.

Answer №5

Utilizing the 'rxjs' library, we are able to import the Subscription module in our Angular project. By creating a new instance of Subscription and assigning it to the variable subscription, we can successfully manage subscriptions within our application.

Answer №6

From the beginning, I ensured that all imports were correctly declared:

import { Subscription } from 'rxjs'

Then, I proceeded to utilize it in the following way:

public subscription : Subscription = new Subscription();

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

Encountering an issue with the date pipe in Angular that prevents

I'm trying to incorporate a date pipe in my AngularJS and Firebase project to display the creation date of a post. However, I am facing an issue where the date does not appear when testing it. Below is my create Post function: createPost() { con ...

I'm experiencing an issue with my website where it appears broken when I build it, but functions properly when I use npm run dev in Next

For my project, I have utilized NextJs, Tailwind, React, and Typescript. It is all set and ready to be hosted. After using "output: export" in next.config.js and running npm run build, the process was successful. However, when viewing my website locally, I ...

Error message in React: "The type 'Window & typeof globalThis' does not have a property named 'ethereum'"

Encountering a problem: Issue with 'ethereum' property on type 'Window & typeof globalThis' In my React project, I'm facing an error. The following code is causing the problem: import { ethers } from 'ethers' cons ...

Uploading videos on Mobile Safari causes the website to refresh automatically

Setting up a photo uploading server on a raspberry pi using Angular with Node.Js and multer has been an exciting project for me. I opted to host it on an unsecured ad-hoc network created by the pi itself so I can easily take it on road trips and store phot ...

Display an error message in the input type file Form Control if the file format is not .doc or .docx

I need a way to display an alert if the user tries to submit a file that is not of type doc or docx. I've implemented a validator for this purpose and would like the alert message (Unacceptable file type) to be shown when the validation fails. Here i ...

Unable to run 'ng serve -o', however 'ng serve' functions correctly

Encountering an issue with Angular when attempting to configure the Micro frontend Framework (module federation) for both the remote and host applications. They are not located in the same workspace. When running the remote app with "ng serve -o", an error ...

Differentiating Layout Routing in Angular 2

In my unique Angular 2 application, I am facing a challenge with the layout. The home page has a completely different layout compared to the rest of the app, which only share a navigation bar. Here are some sample URLs: http://localhost:4200/ <= ...

Send the latest cell parameters from the CellRendererFramework element to the main grid component

Within ag-grid, I am utilizing the cellRendererFramework to render a specific cell. By accessing the params property, I can retrieve the values of the cell from the parent grid component. However, I now have the need to update these params from my cellRend ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Leveraging Global Variables in TypeScript with Node Express

Having issues using global variables in node express when working with typescript. Specifically, trying to use the same global array variable tokenList:tokList across multiple modules and middleware, but haven't been successful so far. Any suggestions ...

encountered an error stating module '@angular/compiler-cli/ngc' could not be located while attempting to execute ng serve

Here is the content of my package.json file: { "name": "cal-euc", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build&qu ...

Guide on setting up global typing for AngularJS in your project

I have been working on a project that initially used the deprecated typings method for incorporating Typescript definitions. I now want to transition to using the @types method instead. Currently, we have a typings.json file located in the root of the pro ...

I'm struggling to find the right Typescript syntax for defining a thunk function that returns a value while using React Redux Toolkit

Currently, I am utilizing TypeScript within a React Redux Toolkit project. While attempting to create an Async Thunk action function that is expected to return a boolean value, I found myself struggling with determining the correct TypeScript syntax: expor ...

What could be causing the issue of custom Angular svg not displaying correctly?

I am struggling to incorporate custom SVGs into my Angular Material project. My method closely resembles what is shown in this stackblitz: https://stackblitz.com/edit/angular-taqtkq-izuc7e?file=app%2Ficon-svg-example.ts Despite attempting various paths, ...

TS2304 TypeScript (TS) Unable to locate the specified name

Encountering an error message stating Cannot find name 'Record'. Do I need to install a specific package for this class? Severity Code Description File Project Line Suppression State Error TS2304 (TS) Cannot find name 'Record ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

Is there a method to automatically create .stories.ts files in Angular Storybook?

I am seeking a way to automatically create a .stories.ts file within a component folder after executing the command ng g component my-component. The desired outcome should resemble this structure: my-component -my-component.component.html . ...

Implementing setState callback in TypeScript with React Hooks

Hello everyone! I am currently working on defining my component types using TypeScript, and I am faced with a challenge. I am trying to set it up so that I can either pass an array of objects or a callback function containing the previous state. Below is t ...