首页 > 解决方案 > Angular 1.5 使用 Subject 获取服务价值

问题描述

我使用 angularjs 1.5 版,目的是使用组件来监听服务更新。

我的服务.ts

export class myService {
   private _myBoolean: Subject<boolean>

  constructor() {
   this._myBoolean = new Subject<boolean>();
  }
   //  
  public get myBoolean(): Observable<boolean>{
    return this._myBoolean;
  }

  public set myBoolean(value: Observable<boolean>) {
   this._myBoolean.onNext(true)
  }

}

我想监听来自服务 myComponent 的布尔更新

export class myComponent ContextComponent {
  public updatedBoolean;

  $inject: string[] = [myService]

  this.updatedBoolean = this.myService.myBoolean   <--- I need to subscribe to the service
}

我尝试使用 angularJS 订阅来自服务的传入更新以更新我的组件变量。

标签: angularjstypescriptrxjs

解决方案


您不能只将 绑定Subject到组件中的变量并期望 angularjs 自动处理它。与更现代的 Angular 不同,在 angularjs 中有摘要循环的概念,摘要循环会影响对范围的更改何时应用于 DOM。这是 angularjs 不使用 native 的原因之一Promise,该$q服务实现了一种特殊类型的 Promise,它集成到 angularjs 摘要循环中。由于Subject(并且Observable通常)postdates angularjs,并且没有直接等效的挂钩到摘要周期,您负责使用Observable并告诉 angularjs 何时处理范围。

这可能是这样的:

export class MyComponent implements ng.IComponentController {

    public static $inject: string[] = [
        '$scope',
        'myService'
    ];

    public updatedBoolean: boolean;

    constructor(private readonly $scope: ng.IScope,
                private readonly myService: MyService) { }

    $onInit() {
        this.myService.myBoolean.subscribe((value) => {
            this.updatedBoolean = value;
            this.$scope.$digest();
        });
    }

}

注意:我不熟悉,ContextComponent所以我在这个例子中切换到使用“标准”angularjs 类型(例如npm install @types/angular@1.5.x)。


推荐阅读