【发布时间】:2018-03-10 04:28:34
【问题描述】:
当服务持有一个值并且组件订阅它时,我正在尝试以角度实现服务组件通信。我正在使用 rxjs 订阅,但我得到了
Uncaught (in promise): Error: No provider for Subscription!
这是我在服务中所做的:
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();
}
}
在组件中:
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();
}
}
组件和服务被捆绑到模块中,然后注入到另一个模块中。
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 {}
显然,我在这里做错了
【问题讨论】:
-
如果你在一个由 Angulars DI 实例化的类中有一个构造函数参数,那么必须有一个匹配的提供者。
constructor(private context: PracticeContextService, private subscription: Subscription)中这个参数的作用是什么? -
订阅不适用于DI,像
import { Subscription} from 'rxjs/Subscription';一样导入。 -
@lyubimov-roman 我实际上是在组件中进行此导入。如果我不必将此依赖项连接到构造函数中的组件,那么正确的使用方法是什么?我在问,因为我发现了一些使用这种方法的例子,但它似乎对我不起作用。
-
为什么要在构造函数中导入,它的目的是什么?
标签: angular typescript rxjs