订阅中的变量更改后,Angular 2 View不会更新

时间:2016-07-18 20:42:44

标签: typescript angular

我遇到一个问题,当我在可观察订阅中更新变量时,我的视图不会改变。我正在尝试显示一个加载微调器,同时我等待后端的响应,然后显示响应,但旋转器不会隐藏。我的订阅如下:

this.isRequesting = "true";
this.questionService.onSubmit(form, this.questions).subscribe( (value) => {
        this._ngZone.run( () => {
             this.fileLocation = JSON.stringify(value);
             console.log(this.fileLocation);
            this.isRequesting = "false";
            console.log(this.isRequesting);
        });
    });

我的这个组件的html如下所示:

<spinner *ngIf="isRequesting=='true'"></spinner>

我可以看到isRequesting更改为&#34; false&#34;在我从后端(Springboot)获得响应后,在我的控制台中,但视图仍然没有改变。微调器来自SpinKit,我修改了这个tutorial,让我的微调器工作。

我试过了:

  1. 教程中的方法(错误中的stopRefreshing()和observable的完整参数)
  2. ngZone强制我的观点更新。
  3. 有没有人有任何关于如何让我的观点更新的想法,或者在我从后端得到回复之后以任何方式让我的微调器隐藏起来?

4 个答案:

答案 0 :(得分:72)

你在控制台上看到任何错误吗? 这可能是因为在更新值后,angular没有运行更改检测。 我认为你不需要ngZone.run,因为它会在角度区域之外运行代码。

this.questionService.onSubmit(form, this.questions).subscribe( (value) => {
            this.fileLocation = JSON.stringify(value);
            console.log(this.fileLocation);
            this.isRequesting = "false";
            console.log(this.isRequesting);
    });

如果由于某种原因你需要在Angular区域之外运行它,那么你应该告知angular通过这种方法之一运行一个变化检测周期。

  • 在set timeout

    中包装isRequesting的更新
    setTimeout( () => this.isRequesting = "false", 0);
    
  • 手动调用更改检测

    import {ChangeDetectorRef} from '@angular/core'
    constructor(private ref: ChangeDetectorRef){}
    
    this.questionService.onSubmit(form, this.questions).subscribe( (value)=> {
        //existing code
        console.log(this.isRequesting);
        this.ref.detectChanges();
    });
    

答案 1 :(得分:15)

您也可以尝试此解决方案:Guide from Thoughtram

简短版本:

 import { ChangeDetectorRef } from '@angular/core';
    ...
    constructor(private cd: ChangeDetectorRef) {}
    ...
    ... .subscribe( () => {
           <yourstuff>
           this.cd.markForCheck();
        }

你很好。

背景:当通过.subscribe()更改值时,angular不会通知它应该运行changedetection。所以你需要自己运行它。

答案 2 :(得分:0)

如果您正在* ngIf表达式中使用它,请记住* ngIf = false不能用作您需要添加的表达式

 <ul *ngIf=" somefunction(x) ? false: true">
 

答案 3 :(得分:0)

您可以通过changeDetection切换(打开/关闭)模板更新。您必须将策略选择放入组件定义中。您可以选择默认或OnPush策略。

@Component({
    selector: '...............',
    templateUrl: '.......html',
    styleUrls: ['..........scss'],
    changeDetection: ChangeDetectionStrategy.Default
})
相关问题