Angularjs 状态绑定

Angularjs state binding

我有 2 个组件(比如组件 A 和组件 B),它们在组件层次结构中相距 很远。我希望根据 组件 B 中的事件切换 组件 A 的可见性。我正在尝试通过两个组件共享的服务传递此状态。

我尝试了几种方法,其中 none 对我有用。我不确定这是预期的还是我做错了什么。

ControlService

@Injectable()
export class ControlService {
    public isOpenState: Boolean = false;

    constructor() { }

    enable() {
        this.isOpenState = true;
    }

    disable() {
        this.isOpenState = false;
    }

    isOpen() {
        return this.isOpenState;
    }

}

方法一

组件 Foo

export class FooComponent implements OnInit {
    private isOpen:Boolean;

    constructor(controlService: ControlService) {
        this.isOpen = controlService.isOpenState;
    }
}

HTML

<div id="wrapper" *ngIf="isOpen"> </div>

方法二

组件 Foo

export class FooComponent implements OnInit {
    private isOpen:Boolean;
    private controlService: ControlService;

    constructor(_controlService: ControlService) {
        this.controlService = _controlService;
    }

    fetchState(){
    }

    ngOnInit() {
        console.log('Hello Component');
    }
}

HTML

<div id="wrapper" *ngIf="controlService.isOpen()"> </div>

方法 3

HTML

<div id="wrapper" *ngIf="controlService.isOpenState"> </div>

None 上面的内容按预期对我有用,组件的状态不反映服务中的状态。 其中哪一个是正确的方法,我在其中缺少什么?如果两者都不是,那么正确的做法是什么?

方法一

export class FooComponent implements OnInit {
    private isOpen:Boolean;

    constructor(controlService: ControlService) {
        this.isOpen = controlService.isOpenState;
    }
}

只更新 this.isOpen 一次。 controlService.isOpenState 的后续更新不会在 FooComponent

中更新

方法二

如果您的 *ngIf 看起来像

应该可以工作
*ngIf="controlService.isOpen()"

方法 3

如果您的 *ngIf 看起来像

应该可以工作
*ngIf="controlService.isOpenState"

首选方法是在服务中使用可观察对象而不是普通属性,这样 Angular 会收到有关更新的通知,而不是更改检测轮询更改。

有关详细信息,请参阅 https://angular.io/docs/ts/latest/cookbook/component-communication.html