Angular 2从组件到服务共享数据并返回到另一个组件
问题描述:
我有组件,我将布尔变量的值设置到服务中,另一个组件中我订购了相同的服务。Angular 2从组件到服务共享数据并返回到另一个组件
问题是我没有得到我订阅的组件2的任何更新。
如果我把组件1中的订阅方法ngOnInit一切工作正常。
非常感谢!
样品
组件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);
}
}
答
如果您在使用@Component
像providers
这
@Component({
selector: 'navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css'],
providers: [SharedService] // <-- here
})
这意味着每个组件将有自己的服务实例。
将此移至@NgModule
内部的AppModule.ts
,则该模块中的服务将保持不变。
您可以阅读时,在组件here注入
非常感谢你:) –