我有一个 Observable 服务,我用它来协调组件之间的数据。在这种情况下,我试图用它来控制哪些组件/ html 一次应该是可见的。
当我将父组件订阅的行为主体的值设置为true时,它会成功显示子组件(transform-addedit)。但是,当我从子组件更新控制此(mapAddingTransformSubj)的服务成员时,即使我在父组件中订阅,视图也不会切换回来。我确实确认父母正在正确接收可观察的价值。
如果有人可以提出更好的方法来做到这一点,我将不胜感激!
父组件html:
<div class="container-fluid custom-container">
<div *ngIf="!addingTransform">
//Some html
<button class="btn btn-default" (click)="addNewTransform()"><span class="glyphicon glyphicon-plus"></span> Add New Transformation</button>
</div>
<div *ngIf="addingTransform">
<transform-addedit></transform-addedit>
</div>
</div>
父组件.ts:
//Toggles whether or not to show the Transformation components
public addingTransform: boolean;
active: boolean = true;
//Subscriptions for map create service
addingTransformSubscription: Subscription;
//Sets the visible component to the transform add/edit component
addNewTransform() {
this.mapAddEditService.setAddingTransform(true);
}
constructor(private _dataService: DataService, private mapAddEditService: MapAddEditService) {
this.addingTransformSubscription = this.mapAddEditService.getAddingTransform().subscribe(addingTransform => this.addingTransform = addingTransform);
}
ngOnInit(): void {
}
ngOnDestroy(): void {
}
}
子组件 .ts:
cancelTransform() {
this.mapAddEditService.setAddingTransform(false);
}
constructor(private _dataService: DataService, private mapAddEditService: MapAddEditService) {
}
ngOnInit(): void {
}
我的部分服务:
@Injectable()
export class MapAddEditService {
private mapAddingTransformSubj = new BehaviorSubject(false);
setAddingTransform(addingTransform: boolean) {
this.mapAddingTransformSubj.next(addingTransform);
}
getAddingTransform() {
return this.mapAddingTransformSubj.asObservable();
}