0

I have a method that makes a query and gets some data.

I know that the data is there because console.log is showing it but it's not been passed to the variable I created so I have add it to an *ngFor loop in the .html of the component.

Here is the code:

...

export class MainComponent {

  queryResult; // results wanted here

  constructor(private myService: MyService) {

    this.testQuery(); // run the method
  }


testQuery() {

    const qry = 'SELECT * FROM mytable';
    this.myService.db.query( qry, ( err, result ) => {
      if ( err ) {
        console.log('err', err);
      } else {
        console.log('result', result); // shows the data
        this.queryResult = result; // result is NOT passed to this.queryResult
      }
    } );
}

How can I pass the result data to this.queryResult?

UPDATE:

I've checked this.queryResult is there's is actually data there.

It looks like this:

console.log(this.queryResult);

And it's returning this:

enter image description here

Is it something to do with the *ngFor then?

Here's that part:

  <ul>
    <li *ngFor="let data of queryResult">
      {{data.City}}
    </li>
  </ul>
joe2020wow
  • 237
  • 5
  • 12

1 Answers1

1

Because you don't give a type to your queryResult, you can not use ngFor. Try this:

loadingData = true;
queryResult: any[] = [];

testQuery() {
    const qry = 'SELECT * FROM mytable';
    this.myService.db.query(qry, (err, (result: any[])) => {
      if ( err ) {
        console.log('err', err);
      } else {
        this.queryResult = JSON.parse(JSON.stringify(result)); // but I think your result is already converted
        this.loadingData = false;
      }
    } );
}

then, you need to use ngIf in your template. Why? Because your html content must be builded when you have the data loaded.

<div *ngIf="!loadingData">
   <div *ngFor=.....>
   </div>
</div>
AlleXyS
  • 2,476
  • 2
  • 17
  • 37
  • Doesn't work. I can see the data in the console but nothing in the .html part of the component – joe2020wow Jun 15 '20 at 08:45
  • updated answer. you need to use an boolean to wait for data, then render the html, because your template is rendered before to load data – AlleXyS Jun 15 '20 at 09:37
  • For some strange reason I have to call the method twice in order to get the data on the .html page...otherwise it would be working – joe2020wow Jun 15 '20 at 10:19