0

I have such a problem.

I am returning data using Http. Everything works checked with the browser, but I cannot display it on the front. I have such a strange problem that I cannot deal with even while debugging.

I have a clientList array and theoretically it should receive data (subscribed).

When calling API, I get undefined. I assigned a button to the HTTP query.

My original query for the button looks like this:

HMTL here:

<button (click)= "getClients()" ></button>

And my component with the method:

import { Component, OnInit } from '@angular/core';
import {MapsAPILoader} from '@agm/core';
import { ClientService } from '../Services/ClientService';
import { Client } from '../Models/Client';
import { HttpClient } from '@angular/common/http';

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

  clientList: Array<Client>;

  constructor(private client: ClientService){}

  ngOnInit(): void {
    // this.getClients();
  }

  // tslint:disable-next-line: typedef
  getClients(){
    this.client.getClients().subscribe(clients => this.clientList = clients);
    this.loopByArray();
  }

     loopByArray(){
      for (let index = 0; index < this.clientList.length; ++index) {
        let value = this.clientList[index];
        console.log(index, value);
      }
    }
}

If I call the button like I wrote, I get undefined. However, if I change only one character while debugging, i.e. I add one more equal sign:

Old :
this.client.getClients().subscribe(clients => this.clientList = clients);

New :
this.client.getClients().subscribe(clients => this.clientList == clients);

And I will play it again (I will press the button), I get clients normally without a problem:

enter image description here

Unfortunately, I add exactly the same error and undefined again (even if I play it several times). I do not understand what is going on. Do you have to generate the array at the very beginning? Because I don't really understand it anymore.

Błażej
  • 125
  • 2
  • 11

2 Answers2

1

modify your getClients function like below. And get knowledge how async/await works

 getClients(){
    this.client.getClients().subscribe(clients => {
         this.clientList = clients;
         this.loopByArray();
    });
  }
Sameer
  • 509
  • 3
  • 16
0

As far as I see you do not understand the difference between = and == and don't know about ===

  • this.clientList = clients will SET value of this.clientList equal to clients. And return value will be undefined
  • this.clientList == clients will COMPARE this.clientList and clients. And the result will be true or false. This will be a loose comparison

read more about the comparison here https://medium.com/jspoint/loose-vs-strict-equality-in-javascript-3e5136720b00

Dmitriy Sakhno
  • 453
  • 3
  • 8