【问题标题】:Angular 1.5 get service value using SubjectAngular 1.5 使用 Subject 获取服务价值
【发布时间】:2020-10-29 12:24:28
【问题描述】:

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

myService.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)
  }

}

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

export class myComponent ContextComponent {
  public updatedBoolean;

  $inject: string[] = [myService]

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

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

【问题讨论】:

  • 什么不起作用? export class myComponent ContextComponent 看起来像一个语法错误,你需要 implementsextends 在那里。在 angularjs 中使用 Observable 对象可能也不会像您期望的那样工作,Observable 不会自动绑定到角度摘要循环中,您必须手动启动摘要循环。
  • 是否可以举个例子使用上面的服务和组件和摘要循环?

标签: angularjs typescript rxjs


【解决方案1】:

我猜你需要订阅:

this.updatedBoolean = this.myService.myBoolean.subscribe(newVal => { yourChanges...});

【讨论】:

    【解决方案2】:

    您不能只将Subject 绑定到组件中的变量并期望 angularjs 自动处理它。与更现代的 Angular 不同,在 angularjs 中有摘要循环的概念,摘要循环会影响对范围的更改何时应用于 DOM。这是 angularjs 不使用原生 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)。

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 2020-05-10
      • 2017-10-11
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多