Angular 2将数据从组件共享到服务并返回到另一个组件
我有一个组件,在其中我将布尔变量的值设置到服务中,还有另一个组件,我在其中订阅了相同的服务 问题是我没有得到订阅的组件2的任何更新 如果我把subscribe方法放在组件1中,一切都会正常工作 多谢各位 样品 组成部分1Angular 2将数据从组件共享到服务并返回到另一个组件,angular,observable,angular2-services,angular2-observables,Angular,Observable,Angular2 Services,Angular2 Observables,我有一个组件,在其中我将布尔变量的值设置到服务中,还有另一个组件,我在其中订阅了相同的服务 问题是我没有得到订阅的组件2的任何更新 如果我把subscribe方法放在组件1中,一切都会正常工作 多谢各位 样品 组成部分1 import {Component} from '@angular/core'; import {SharedService} from '../shared/shared.service'; @Component({ selector: 'welcome',
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);
}
}
如果您在@Component中像这样使用提供者
@组成部分{
选择器:“导航”,
templateUrl:'./navigation.component.html',
样式URL:['./navigation.component.css'],
提供者:[共享服务]//