为什么我无法在 Angular 中订阅来自不同模块的可观察对象(而 setter 也有效)

Why am I not able to subscribe to an observable from a different module(while setter also works) in Angular

我正在尝试跨模块工作 - 我在一个模块中编写了一个服务

sharedService

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
private paramsSource = new Subject<any>();
current_params$ = this.paramsSource.asObservable();
set_current_params( params:any) {
  this.paramsSource.next(params);
}
get_current_params(){
  console.log(this.current_params$)// returns {'id':'15'} on console
  return this.current_params$
}

我从一个并行模块调用它,我可以在其中设置当前参数 通过构造函数调用服务。但是,getter 似乎不适用于同一个模块。订阅似乎不起作用。它似乎 return 是可观察的,但我无法订阅它。

my component.ts

import { Component, OnDestroy } from '@angular/core';
import { SharedService } from '../../../core/shared/shared.service';
import { Subscription, Observable } from 'rxjs';



@Component({
  selector: '[app-myComponent]',
  templateUrl: './myComponent.component.html',
  styleUrls: ['./myComponent.component.scss']
})
export class MyComponentComponent implements AfterViewInit {
constructor(
    private shared: SharedService
) { }
ngOnInit() {
  this.shared.set_current_params({'id':'15'});
{
ngAfterViewInit() {
   console.log(this.sharedService.get_current_params());//log line 1
   this.shared.get_current_params().subscribe(current_params => {
   console.log('anything'); //log line 2
   console.log(current_params); //log line 3 
})

}

记录第 1 行 returns 在第一行是一个可观察的 但是,订阅 return 什么都没有,日志 2 和 3 是空的。

我尝试从不同的模块进行相同的订阅,getter 也有效。为什么它没有在 getter 中的这个组件中被拾取?

  1. 在共享模块中,您需要将共享服务添加为提供者。
  2. 在包含 MyComponentComponent 的模块中,您需要导入 SharedModule。 您应该包括 SharedModule 的代码和带有 MyComponentComponent 的模块以获得完整的答案

问题是您在订阅它之前设置了一个值。如果您将代码从 ngOnInit 移至 ngAfterViewInit,并将代码从 ngAfterViewInit 移至 ngOnInit,那么您的订阅将有效。请参阅 StackBlitz example. As mentioned in my comment above, if you need to support the ability to get the latest value upon subscription, i.e. the last value that was emitted before you subscribed, then you need to use either a BehaviorSubject or a ReplaySubject 而不是主题。