Issue
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
Solution
In your service, you could first of all change rxjs imports like this :
import { Observable, Subscription } from 'rxjs/Rx';
I already had an issue when importing { Observable } from 'rxjs/Observable'. Now I am careful with this :P ! (I should maybe dig further to find out what really happens behind the scene.)
Then, as already said Lyubimov Roman in its comment above, you should not import rxjs subscription through the constructor. I don't understand your answer to Lyubimov's comment. Could you please provide us the examples you mention in order to let us figure out what is intended ?
If you need to use an subscription object in your component, just import it like this :
import { Subscription } from 'rxjs/Rx';
Answered By - Arpp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.