Angular 2 View will not update after variable change in subscribe

后端 未结 4 1632
耶瑟儿~
耶瑟儿~ 2020-11-27 04:26

I have a problem where my view will not change when I update my variable in my observable subscription. I am trying to show a loading spinner while I wait for a response fro

相关标签:
4条回答
  • 2020-11-27 04:35

    are you seeing any error on console? This could be due to fact that angular is not running change detection after you have made updates to value. I think you don't need ngZone.run as it will run code outside the angular zone.

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

    If due to some reason you need to run this outside Angular zone, then you should inform angular to run a change detection cycle by either of this method.

    • just wrap update of isRequesting in set timeout

      setTimeout( () => this.isRequesting = "false", 0);
      
    • invoking change detection manually

      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();
      });
      
    0 讨论(0)
  • 2020-11-27 04:37

    You can switch (on/off) template updating via changeDetection. You have to put your choice of strategy into component definition. You can choose Default or OnPush strategy.

    @Component({
        selector: '...............',
        templateUrl: '.......html',
        styleUrls: ['..........scss'],
        changeDetection: ChangeDetectionStrategy.Default
    })
    
    0 讨论(0)
  • 2020-11-27 04:39

    if you are using it in expression *ngIf remember *ngIf = false will not work as expression you need to add

    <ul *ngIf=" somefunction(x) ? false: true">
    
    0 讨论(0)
  • 2020-11-27 04:41

    You can also try this solution: Guide from Thoughtram

    Short version:

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

    and you are good.

    Background: when changing a value via .subscribe() angular does not notify that it should run changedetection. So you need to run it yourself.

    0 讨论(0)
提交回复
热议问题