2

I have a Component-directive that I use to show a div with some information.

This component is called SitesComponent and is included in a page. The main behavior of the SitesComponent is fine, except for this:

  • I have an API call to a backend where I return some data, the backend call is executed well and I received the information but the variable is not updated on the template

This is my code:

import { Component } from '@angular/core';
import { MyApi } from '../../myapi';

@Component({
  selector: 'sites-component-widget',
  templateUrl: './sites-component.html',
  styleUrls: ['./sites-component.scss'],
})
export class SitesComponent {
    data: any = [];
    constructor(private api: MyApi}

    ngOnInit() {
        var _ = this
          this.api.company_sites(this.companyId).subscribe(
            response => {
                //this.data = response; 
                this.data = [1,2,3]; 
            },
            error => {
              console.log("error")
            }
          )
        }        
    }
}

I tried to update the variable data using the received response and also using static data. The UI is never updated with the changes inside the API call.

I'm using angular http client:

import { HttpClient } from "@angular/common/http";

But it didn't work neither

  • What I'm doing wrong ?

I read about using observables or promises for the API, I tried both ways and I couldn't find a solution... My UI is never updated when I update the variable inside the .subscribe() or .then() functions

EDIT: I forgot to add my html, but as far it is just 3 lines:

<div class="sites-online-widget">
    **{{data}}**
</div>

Summary of my issue:

If I do this the variable is updated on the template

ngOnInit() {
    this.data = [1,2,3,4]
}

but when I do this, the variable is not updated on the template:

ngOnInit() {
    var _ = this
      this.api.company_sites(this.companyId).subscribe(
        response => {
            this.data = [1,2,3]; 
        }
      )}        
}

Final Edit

Found a solution that worked in another question, I tried to close this one.

The question that solved my issue was this:

Angular 2 View will not update after variable change in subscribe

3 basic steps:

// Import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core';

// Add ChangeDetectorRef to constructor
constructor(private cd: ChangeDetectorRef) {}

// Call markForCheck at the end of the subscribe function
this.cd.markForCheck();

My code ended like:

import { Component } from '@angular/core';
import { MyApi } from '../../myapi';

// 1
import { ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'sites-component-widget',
  templateUrl: './sites-component.html',
  styleUrls: ['./sites-component.scss'],
})
export class SitesComponent {
    data: any = [];
    constructor(
      private api: MyApi,
      // 2
      private cd: ChangeDetectorRef}

    ngOnInit() {
        var _ = this
          this.api.company_sites(this.companyId).subscribe(
            response => {
                this.data = response; 
                // 3
                this.cd.markForCheck()
            },
            error => {
              console.log("error")
            }
          )
        }        
    }
}
AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
  • can you post your html – LLai Jan 02 '18 at 15:50
  • @Llai yes, I forgot to add it but right now I'm just showing the value inside the variable – AlvaroAV Jan 02 '18 at 15:52
  • can you do an `ngif` ? Show the div if the data is not null or something? – Bhavik Patel Jan 02 '18 at 16:00
  • I did, data is initialized to empty array `[]`. If I do ngIf to show if data is empty, it is, even after receiving the response. Like I said, it seems the main issue is that the variable **data** is not being updated inside the **susbcribe** method. And I'm 100% sure the code goes inside the subscribe method because I'm printing the result of the API – AlvaroAV Jan 02 '18 at 16:03
  • The main issue is the value does not updating in your html. You have the array initialized as `[]` so your html is rendering an empty array. So do an `ngif` to show your div only when the array is NOT empty. – Bhavik Patel Jan 02 '18 at 16:06
  • I already did, and the variable is not getting updated, the div is always hidden – AlvaroAV Jan 02 '18 at 16:07
  • try this `Observable.interval(10000) .takeWhile(() => !stopCondition) .subscribe(i => { // change variable data here })` and see if the data change – Alber Jan 02 '18 at 16:09
  • also, datatype of `data` shouldn't by of `any`. It should be an array. And could you please tell me what condition are you checking in `ngif`. And there are no console errrors whatsoever? – Bhavik Patel Jan 02 '18 at 16:14
  • I need a variable with empty list, to store the array returned by the backend. My issue is that the template is not updated when I change the value of **data** inside the **subscribe** method of the API. On the ngif I was checking the length of the array, no console errors, if I change the variable elsewhere, the ngIf behaves as expected – AlvaroAV Jan 02 '18 at 16:15
  • int the array as undefined and check that instead – Alber Jan 02 '18 at 16:17
  • do you resolve the problem? – Alber Jan 02 '18 at 16:32
  • Nope, still struggling with it. I initialized to undefined but it was the same – AlvaroAV Jan 02 '18 at 16:42

1 Answers1

1

implement OnInit

import { OnInit } from '@angular/core';

export class SitesComponent implements OnInit {}
AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
Alber
  • 175
  • 11
  • My code from `ngOnInit()` is being executed. I get the response of the API, but the UI is not updated when the variable **data** changes inside the **subscribe** method. Is that right ? I tried adding the code you suggested but nothing changes – AlvaroAV Jan 02 '18 at 15:49
  • pls show the html code, and check if response is not undefined, `console.log(response)`. – Alber Jan 02 '18 at 15:52
  • I'm 100% sure the response is not empty, I already checked that, the response has data, I printed it to console before posting the question. The problem is when I change the **data** variable inside the subscribe method nothing happens on the UI (even when I do `this.data = [1,2,3]`) – AlvaroAV Jan 02 '18 at 15:55