【问题标题】:Angular component updates variable in view only after I move the mouse仅在我移动鼠标后,角度组件才更新视图中的变量
【发布时间】: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


【解决方案1】:

这里有一个有趣的点:https://stackoverflow.com/a/41241646/1030207

this.methodCallingAThirdPartyLibrary() 正在返回通过调用第三方库的方法返回的 Promise,因此可能一切都在 Angular 的控制之外发生。

明天早上(这里是 23.44)我会尝试将内部调用包装成 zone.run

【讨论】:

  • 这是真正的罪魁祸首,它奏效了!我将在明天允许我这样做时将此标记为答案。
【解决方案2】:

由于我无法实现您的服务,因此我在下面的代码中使用 ngDoCheck 和 ChangeDetectionStrategy 在组件中发生任何更改时进行记录,如下所示

import {Component, NgModule ,ChangeDetectionStrategy,ngDoCheck} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule} from '@angular/forms';
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
        <input [(ngModel)]="someValue" />
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class App implements ngDoCheck {
  someValue:any;
  name:string;
  constructor() {
    this.name = 'Welcome to Change Detection Demo'
  }
  ngDoCheck(){
    console.log(this.someValue);

    }
}

我使用了一个文本框来检测组件的变化。

LIVE DEMO

【讨论】:

  • 谢谢,不过我不确定这是否是一个很好的例子:用键盘打字似乎与移动鼠标具有相同的效果,从而使测试无效。
  • 不完全是。通过设置超时调用尝试使用一些异步方法。它也会记录
猜你喜欢
  • 2017-08-14
  • 1970-01-01
  • 2022-01-09
  • 2015-11-28
  • 2014-06-03
  • 2012-12-25
  • 1970-01-01
  • 2012-08-02
  • 2015-07-31
相关资源
最近更新 更多