2

This question is a based on this one (the solution provided didn't work): Angular 4: Update template variable after API call [duplicate]

I'm tring to update view after an api call using HttpClient, but my html template doesn't update.

product.ts

export class ProductModel {
ID:number;
Name:String;
CategoryName:String;
Price:number;
OldPrice:number;
IsNew:Boolean;
InStock:Boolean;
Image:String;

}

products.service.ts

import { Component, Injectable, Injector } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { HttpClient, HttpParams, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';

import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map} from 'rxjs/operators';

import { ProductModel } from 'src/app/models/product';

@Injectable()
export class ProductsService { 

  constructor(private http: HttpClient) { } 

  GetProducts(): Observable<ProductModel[]>{      
      return this.http.get<ProductModel[]>('https://myapi.com/api/products');
    } 
}

products.component.ts

import { Component, OnInit, ViewEncapsulation, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatSidenav } from '@angular/material/sidenav';
import {MatExpansionModule} from '@angular/material/expansion';

import {Observable} from 'rxjs';
import { map } from 'rxjs/operators';

import * as $ from 'jquery';

import {ProductsService} from '../../services/products.service';

import { ProductModel } from 'src/app/models/product';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
  providers: [ProductsService],
  encapsulation: ViewEncapsulation.None 
})
export class ProductsComponent implements OnInit { 
  @ViewChild('sidenav') sidenav: MatSidenav;

  public productsList = [];
  private reason:string;

  constructor(private _productsService: ProductsService, 
    private _ref: ChangeDetectorRef) {  
  }

  ngOnInit(){ 
    this.GetProducts();  
    console.log(this.productsList);
  } 

  close(reason: string) {
    this.reason = reason;
    this.sidenav.close();
  }

  GetProducts(){  
    this._productsService.GetProducts()
    .subscribe(
      response => {
        this.productsList = response; 
        this._ref.markForCheck();
        console.log(this.productsList);
      },
      error => { console.log(error) }
    );  
  }  

}

products.component.html

 <ul>
  <li *ngFor="let prod of productsList" >
    Id: {{prod.ID}} <br>
    Name: {{prod.Name}} <br>
    CategoryName: {{prod.CategoryName}} <br>
    Price: {{prod.Price}} <br>
    OldPrice: {{prod.OldPrice}} <br>
    IsNew: {{prod.IsNew}} <br>
    InStock: {{prod.InStock}} <br>
    Image: {{prod.Image}} <br>
  </li>
</ul>

package.json

{
  "name": "smak",
  "version": "0.0.0",
  "scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},
"private": true,
"dependencies": {
  "@agm/core": "^1.0.0-beta.3",
  "@angular/animations": "^6.0.4",
  "@angular/cdk": "^6.1.0",
  "@angular/common": "^6.0.4",
  "@angular/compiler": "^6.0.4",
  "@angular/core": "^6.0.4",
  "@angular/forms": "^6.0.4",
  "@angular/http": "^6.0.4",
  "@angular/material": "^6.1.0",
  "@angular/platform-browser": "^6.0.4",
  "@angular/platform-browser-dynamic": "^6.0.4",
  "@angular/router": "^6.0.4",
  "core-js": "^2.5.4",
  "hammerjs": "^2.0.8",
  "jquery": "^3.3.1",
  "rxjs": "^6.2.1",
  "zone.js": "^0.8.26"
},
  "devDependencies": {
  "@angular-devkit/build-angular": "~0.6.3",
  "@angular/cli": "~6.0.3",
  "@angular/compiler-cli": "^6.0.4",
  "@angular/language-service": "^6.0.4",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/jquery": "^3.3.2",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~1.4.2",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1",
  "typescript": "~2.7.2"
}
}

See my console.log view console log

If u see the my console log my variable is being affected (inside subscription) but outside subscription my variable is being empty.

Has anyone had the same problem? How can I solve? Is this a bug?

Best Regards,

Luís Ferreira
  • 33
  • 1
  • 1
  • 4
  • What happens when you call `this.productsList = this.productsList.slice()` immediately assigning it to the response? This kind of forces the array to get a completely new reference. – Nicholas Reynolds Jun 14 '18 at 10:14
  • 1
    your productsList has only two properties: "Category" and "Products". I can't see nothing like "id" or "name" or "CategoryName". I'm sure that you have errors in console – Eliseo Jun 14 '18 at 10:26
  • I tried but still doesn't work @Nicholas Reynolds – Luís Ferreira Jun 14 '18 at 10:38
  • I updated the question with my model and html, still doesn't work @Eliseo – Luís Ferreira Jun 14 '18 at 10:38
  • To add to @Eliseo's comment, you shouldn't receive any errors in the console, but it does look as though you are trying to reference the properties in the sub-array. You could somehow set up a second for loop in your template to loop through each `Products` array for every item in the `ProductsList` array. – Nicholas Reynolds Jun 14 '18 at 10:41

3 Answers3

4

I had the same issue, it solved using this line of code when the response is retrieved.

    this.changeDetector.detectChanges();

in your case, getProducts should be like this:

GetProducts(){  
    this._productsService.GetProducts()
    .subscribe(
      response => {
        this.productsList = response; 
        this._ref.detectChanges();
        console.log(this.productsList);
      },
      error => { console.log(error) }
    );  
  }  

Another Solution:

it might be a zone conflict while detecting the changes

add NgZone to your constructor

constructor( 
          ...
             private zone:NgZone 
          ...
           ) {}

then your method should look like this:

GetProducts(){  
    this._productsService.GetProducts()
    .subscribe(
      response => {
        this.zone.run(() => { // <== execute the changes in this callback.
            this.productsList = response; 
            console.log(this.productsList);
        });
      },
      error => { console.log(error) }
    );  
  }  
Raed Khalaf
  • 1,997
  • 2
  • 13
  • 29
  • I changed, but unfortunately it did not work for me @Raed Khalaf – Luís Ferreira Jun 14 '18 at 09:45
  • still don't work... i updated the question with my package.json, maybe I'm using a unstable version? @Raed Khalaf – Luís Ferreira Jun 14 '18 at 10:22
  • @RaedKhalaf, see my comment. I think that the problem is not about ngZone (the ngZone is using when you change something outside Angular) or splice – Eliseo Jun 14 '18 at 10:28
  • a curious thing the angular creates six li's in html that correspond of size of array but he doens't bring the values, if you see my model... I don't see any problem @Eliseo – Luís Ferreira Jun 14 '18 at 10:46
1

@LuisFerreira, I must supouse you received some like [{Category:"Cereails",Products:[{Id:1,Name:"Trigo",...},{Id:2,Name:"Maiz",...}]

So you must make two *ngFor

<ul *ngFor="let item of productList">
  <!--item is, e.g. {Category:"Cereails",Products:[{Id:1,Name:"Trigo",...} --> 
  <li *ngFor="let prod of item.Products" >
    <!-- prod is,e.g. {Id:1,Name:"Trigo",...} -->
    Id: {{prod.ID}} <br>
    Name: {{prod.Name}} <br>
    CategoryName: {{item.Category}} <br> <!--see that I use item.Category here -->
    Price: {{prod.Price}} <br>
    OldPrice: {{prod.OldPrice}} <br>
    IsNew: {{prod.IsNew}} <br>
    InStock: {{prod.InStock}} <br>
    Image: {{prod.Image}} <br>
  </li>
</ul>

And forget ChangeDetectorRef or ngZone

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

If you only ever care about the the items within the Products array, you can bypass having to use two *ngFor loops by simply selecting and flattening the Products array.

GetProducts() {  
    this._productsService.GetProducts().subscribe(response => {
        // Essentially the same as a SelectMany() in linq
        this.productsList = [].concat.apply([], response.map(p => p.Products)); 
    }, error => { console.log(error) });  
}

This makes your productsList an array with each element being a single product. Now you can access all the properties of the products and only have one list/*ngFor in your template!