gpt4 book ai didi

Angular + rxjs : No provider for Subscription

转载 作者:行者123 更新时间:2023-12-01 08:49:23 24 4
gpt4 key购买 nike

当服务持有一个值并且组件订阅它时,我正在尝试以 Angular 实现服务组件通信。我正在使用 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();
}
}

然后将组件和服务捆绑到模块中,然后将其注入(inject)另一个模块。
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 {}

显然,我在这里做错了什么

最佳答案

只需删除 private subscription: Subscription来自构造函数并将其放入类的属性中。

关于 Angular + rxjs : No provider for Subscription,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com