角度-变量在订阅中更改后不会在视图中更新

时间:2020-05-26 17:33:46

标签: angular rxjs observable

如果我做这样的事情:

component.html

<input type="button" (click)="emit()">Click to start emitting!</input>
{{decimalNumber | number:'1.1-1'}}

component.ts

ngOnInit(): void {
 this.myService.decimalNumberEmitter$.subscribe(value => {
   console.log('New value is', value);
   this.decimalNumber = value;
 });
}
emit(){
   this.myService.startEmitting();
}

myService.service.ts

decimalNumberEmitter$ = new BehaviorSubject<number>(0.0);
startEmitting() {
   for (let index = 1; index < 11; index++) {
    this.decimalNumberEmitter$.next(index / 10);
   }
}

一旦执行了前面的代码,控制台日志:

新值为0

新值为0.1

...

新值为1

但是变量(decimalNumber)根本没有更新。其值为0.0。

我已经尝试在组件html中执行以下操作,但是没有运气:

{{this.myService.decimalNumberEmitter$ | async }}

我也尝试手动检测更改,但也没有运气-类似以下内容:

constructor(private cd: ChangeDetectorRef) {}
...
... .subscribe( () => {
       [my code]
       this.cd.markForCheck();
    }

任何人都可以对此有所了解??预先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

On my repro on stackblitz可以正常工作,但是我看不出有什么不同的哈哈。

这里是代码,以防万一。

service.ts

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable()
export class MyServiceService {
  decimalNumberEmitter$ = new BehaviorSubject<number>(0.0);

  startEmitting() {
    for (let index = 1; index < 11; index++) {
      this.decimalNumberEmitter$.next(index / 10);
    }
  }
}

component.ts:

import { Component, OnInit } from "@angular/core";
import { MyServiceService } from "./my-service.service";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  decimalNumber;
  constructor(private _myService: MyServiceService) {}

  ngOnInit() {
    this._myService.decimalNumberEmitter$.subscribe(val => {
      this.decimalNumber = val;
      console.log("decimalNumber = ", this.decimalNumber);
    });
  }

  emit() {
    this._myService.startEmitting();
  }
}

component.html:

<input type="button" (click)="emit()" value="Click to start emitting!">
{{decimalNumber | number:'1.1-1'}}

我只是将输入更改为一个值(也可以使其像<button..></button>一样。)

答案 1 :(得分:0)

尝试使用模板中的流,则根本不需要ngOnInitthis.myService.decimalNumberEmitter$.subscribe

<input type="button" (click)="emit()">Click to start emitting!</input>
<ng-container *ngIf="myService.decimalNumberEmitter$ | async as decimalNumber">
  {{decimalNumber | number:'1.1-1'}}
</ng-container>