1

I used observable to get a list of data from API, but data binding does not work after using observable, and my variable does not change in HTML ...

I also used the fetch method, instead of observable, but the result did not matter...

my component.ts:

import { Component, OnInit } from '@angular/core';
import { PostApiService } from '../../services/post-api.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {

  public items: any;
  isLoading = false;
 
  constructor(
    private apiService: PostApiService,
  ) { }

 
  ngOnInit(): void {
    this.getPosts()
  }

  getPosts(): void {
    this.isLoading = true;
    this.apiService.fetchPosts().subscribe(
      (result: any) => this.setItems(result.body),
      (error) => console.log("Error happened" + error),
      () => console.log("the subscription is completed")
    );
  }

  setItems(item: any) {
    console.log('set Items function');
    console.log(item);// data is correct here
    this.items = item; 
    this.isLoading = false;
  }

  
}

my component html:

    <p *ngIf="isLoading">Loading ...</p>

    <div class="row">
        <div *ngFor="let item of items" class="col-lg-6 col-md-6">
            <div class="single-blog-post-item">
                <div class="post-image">
                    <a routerLink="/field/view/1">
                        <img src="g" alt="image">
                    </a>
                    <!-- <div class="date">
                        <span>January 29, 2020</span>
                    </div> -->
                </div>

                <div class="post-content">
                    <span class="category">hghghghghgh</span>
                    <h3><a routerLink="/field/view/1">hhthutydtuyiuyvt</a></h3>
                    <a routerLink="/field/view/1" class="details-btn">{{"learnMore"|translate}}</a>
                </div>
            </div>
        </div>
    </div>
    

The result is the following: Loading ...

ingenious
  • 764
  • 2
  • 8
  • 24
  • Where do you have two way data binding? Do you get response from server, and it has data (not empty array)? – Bojan Kogoj Nov 23 '21 at 12:30
  • 1
    You have defined `let item of items` in the HTML file. Where are you using the values from item in the HTML? – Lenzman Nov 23 '21 at 12:33
  • can you share fetchPosts() service method here? I think you are not getting data from server. Where do you have use two way data binding? – Madeefar Abbas Nov 23 '21 at 12:38
  • The server response is not empty (logged in `setItems` method ). but you can check `isLoading` variable. This variable is not bound either ... – ingenious Nov 23 '21 at 16:49

1 Answers1

1

My problem soved by set changeDetection configuration to Default in the app.component.ts

from :

Angular 8 Metronic binding not updating

ingenious
  • 764
  • 2
  • 8
  • 24