Angwise 2父视图在Observable更改后未更新

时间:2016-10-19 08:40:38

标签: angular rxjs angular2-template angular2-services angular2-observables

我有一个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();
    }

1 个答案:

答案 0 :(得分:0)

刚刚解决了这个问题,这是一个愚蠢的问题

我意识到ngIf检查init,因此绑定到每个父组件html div中的[hidden]而不是ngIf属性修复了我的问题。