-2

モジュール間で作業しようとしています - モジュールにサービスを書きました

共有サービス

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$
}

コンストラクターを介してサービスを呼び出すことにより、現在のパラメーターを設定できる並列モジュールからこれを呼び出します。ただし、ゲッターは同じモジュールからは機能しないようです。サブスクリプションは機能していないようです。オブザーバブルを返すようですが、サブスクライブできません。

私の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 は最初の行でオブザーバブルを返しますが、サブスクライブは何も返さず、ログ 2 と 3 は空です。

別のモジュールから同じサブスクリプションを試してみると、ゲッターも機能します。ゲッターだけでこのコンポーネントで取り上げられないのはなぜですか?

4

2 に答える 2