Angular + rxjs:没有订阅提供者

vit*_*lym 4 rxjs typescript angular

我正在尝试以 angular 实现服务组件通信,当服务持有一个值并且组件订阅它时会发生变化。我正在使用 rxjs 订阅,但我得到了

Uncaught (in promise): Error: No provider for Subscription!
Run Code Online (Sandbox Code Playgroud)

这是我在服务中所做的事情:

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();
 }
}
Run Code Online (Sandbox Code Playgroud)

并在组件中:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将组件和服务捆绑到模块中,然后将其注入到另一个模块中。

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 {}
Run Code Online (Sandbox Code Playgroud)

显然,我在这里做错了

小智 14

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


小智 1

在您的服务中,您可以首先像这样更改 rxjs 导入:

import { Observable, Subscription } from 'rxjs/Rx';
Run Code Online (Sandbox Code Playgroud)

从“rxjs/Observable”导入 { Observable } 时我已经遇到了问题。现在我对此很小心:P!(我也许应该进一步挖掘以找出幕后到底发生了什么。)

然后,正如 Lyubimov Roman 在上面的评论中所说,您不应该通过构造函数导入 rxjs订阅。我不明白你对柳比莫夫评论的回答。您能否向我们提供您提到的示例,以便我们弄清楚其意图是什么?

如果您需要在组件中使用订阅对象,只需像这样导入它:

import { Subscription } from 'rxjs/Rx';
Run Code Online (Sandbox Code Playgroud)