Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular + rxjs: No provider for Subscription

I'm trying to implement a service-component communication in angular, when service holds a value and component subscribes to it change. I'm using rxjs Subscription, but I'm getting

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

Here is what I'm doing in a 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 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();
  }
}

Component and service are than bundled into module, which is later 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 {}

Apparently, I'm doing something wrong here

like image 242
vitalym Avatar asked Dec 02 '22 12:12

vitalym


1 Answers

Just remove private subscription: Subscription from constructor and put it in attribute of the class.

like image 169
Carlos Eduardo Guedes Lourenço Avatar answered Dec 22 '22 12:12

Carlos Eduardo Guedes Lourenço