The problem
I have a component with a subscription to an Observable. The value of myValue
gets updated in the template only after I move the mouse over the browser window.
The strangest thing is that the two console.log
work fine.
- I reload the page keeping the mouse static
- I can see the updated value in the console
- The template still shows the 'defaultValue' value
- I move the mouse, and the template shows the updated value I was already seeing in the console.
I managed to make it work with ChangeDetectorRef
and .detectChanges()
, but it seems as wrong as using $scope.apply()
in AngularJS when you don't know where's the problem.
my-component.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { HelperService } from 'path';
@Component({
selector: 'my-selector',
templateUrl: 'my-component.component.html'
})
export class MyComponent implements OnDestroy, OnInit {
myValue: string;
private subscription: Subscription;
constructor(
private helperService: HelperService
) {
//
}
ngOnInit() {
this.myValue = 'defaultValue';
this.subscription = this.helperService.getNewValue$().subscribe((newValue) => {
console.log('pre', this.myValue);
this.myValue = newValue;
console.log('post', this.myValue);
});
}
ngOnDestroy() {
if (this.subscription !== undefined ) {
this.subscription.unsubscribe();
}
}
}
helper.service.ts
getNewValue$(): Observable<string> {
return Observable.fromPromise(this.methodCallingAThirdPartyLibrary());
}
my-component.component.html
debug: {{ myValue }}