【发布时间】:2017-06-12 12:59:29
【问题描述】:
问题
我有一个订阅 Observable 的组件。 myValue 的值只有在我将鼠标移到浏览器窗口上后才会在模板中更新。
最奇怪的是这两个console.log工作正常。
- 我重新加载页面以保持鼠标静止
- 我可以在控制台中看到更新后的值
- 模板仍显示“defaultValue”值
- 我移动鼠标,模板显示我已经在控制台中看到的更新值。
我设法使它与ChangeDetectorRef 和.detectChanges() 一起工作,但是当您不知道问题出在哪里时,它似乎与在AngularJS 中使用$scope.apply() 一样错误。
我的组件.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());
}
我的组件.component.html
debug: {{ myValue }}
【问题讨论】:
-
您的服务是做什么的。它是否按顺序发送数据?
-
编辑了从 HelperService 添加相关代码的问题
-
控制台打印了什么?
-
pre defaultValue 发布新值
标签: angular typescript observable