Reputation: 241
If I do something like this:
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);
}
}
Once the previous code is executed console logs:
New value is 0
New value is 0.1
...
New value is 1
However variable (decimalNumber) is not getting updated at all. Its value is 0.0.
I've tried doing something like following in my component html but with no luck:
{{this.myService.decimalNumberEmitter$ | async }}
Also I tried manually detecting the change but with no luck as well - something like following:
constructor(private cd: ChangeDetectorRef) {}
...
... .subscribe( () => {
[my code]
this.cd.markForCheck();
}
Anyone can shed some light on this?? Thanks in advance for any help!
Upvotes: 0
Views: 164
Reputation: 13539
try to use the stream in the template, then you don't need ngOnInit
with this.myService.decimalNumberEmitter$.subscribe
at all.
<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>
Upvotes: 0
Reputation: 4987
On my repro on stackblitz it works fine, but i cannot see what's different haha.
Here is the code just in case.
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'}}
I just changed the input to take a value (could make it like <button..></button>
as well).
Upvotes: 1