0
ブール変数の値をサービスに設定するコンポーネントと、同じサービスにサブスクライブしている別のコンポーネントがあります。コンポーネント2からサービスへのデータ共有と別のコンポーネントへの返信
問題は、私が購読しているコンポーネント2のアップデートが得られていないことです。
私がコンポーネント1のngOnInitにsubscribeメソッドを置くと、すべて正常に動作します。
ありがとうございました!
サンプル
コンポーネント1
import {Component} from '@angular/core';
import {SharedService} from '../shared/shared.service';
@Component({
selector: 'welcome',
templateUrl: './welcome.component.html',
styleUrls: ['./welcome.component.css'],
providers: [SharedService],
})
export class WelcomeComponent {
constructor(private sharedService: SharedService) {}
contentClicked(){
this.sharedService.setSaveBtnStatus(true);
}
}
コンポーネント2
import {Component} from '@angular/core';
import {SharedService} from '../shared/shared.service';
@Component({
selector: 'navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css'],
providers: [SharedService]
})
export class NavigationComponent {
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.sharedService.getSaveBtnStatus().subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('finished')
);
}
}
サービス
import {Injectable} from "@angular/core";
import { Subject } from 'rxjs/Subject';
import {Observable} from "rxjs/Observable";
@Injectable()
export class SharedService{
private showSaveBtn = new Subject<boolean>();
getSaveBtnStatus(){
return this.showSaveBtn.asObservable();
}
setSaveBtnStatus(value: boolean){
this.showSaveBtn.next(value);
}
}
ありがとうございました。 –