0
    import { Component, OnInit } from '@angular/core';
    import { GridOptions } from 'ag-grid';
    import { Owner } from '../owner';
    import { OwnerService } from '../owner.service';
    import { error } from 'util';

    @Component({
      selector: 'app-owner-list',
      templateUrl: './owner-list.component.html',
      styleUrls: ['./owner-list.component.css']
    })

    export class OwnerListComponent implements OnInit {

      owners: Owner[];
      errorMessage: string;
      private gridOptions: GridOptions;

      ngOnInit(): void {
      }

      constructor(private ownerService: OwnerService) {
        this.initialiseOwnerGrid();
      }

      private initialiseOwnerGrid() {
        this.gridOptions = <GridOptions>{};
        this.gridOptions.columnDefs = [
          { headerName: 'ID', field: 'id' },
          { headerName: 'First Name', field: 'firstName' },
          { headerName: 'Last Name', field: 'lastName' },
          { headerName: 'Address', field: 'address' },
          { headerName: 'City', field: 'city' },
          { headerName: 'Telephone', field: 'telephone' },
          { 
            headerName: 'Pets', 
            field: 'pets',
            cellRenderer : (params) => params.pet.name
           }
        ];

        this.getOwners();
       // console.log("Owner :"+this.owners[0].firstName);
        this.gridOptions.rowData = this.owners; 
      }


      getOwners() {
        this.ownerService.getOwners().subscribe(
          ownersList => {
            this.owners = ownersList;
            console.log("Owner :"+ ownersList[0].pets[0].name);
          });

          console.log("Owner :"+ this.owners[0].pets[0].name);
      }
 }

In the above code , i am getting correct value for the line "console.log("Owner :"+ ownersList[0].pets[0].name);" but getting undefined value for the owner in the line "console.log("Owner :"+ this.owners[0].pets[0].name); }"

I am not able to figure out why it is so. Please help me with the above.

Ishant Gaurav
  • 1,183
  • 2
  • 13
  • 32
  • 1
    The `console.log("Owner :"+ this.owners[0].pets[0].name);` line is outside of your subscribe block. Therefore it is getting executed before the ownersList is actually returned. – peinearydevelopment Feb 19 '18 at 15:52
  • How to make sure that first observables return the data and then this line is executed – Ishant Gaurav Feb 19 '18 at 16:01

1 Answers1

0

Observable are asynchronous.

the expression: console.log("Owner :"+ this.owners[0].pets[0].name); gets called in the same tick before the subscription is called. Therefore you are getting undefined.

 getOwners() {
    this.ownerService.getOwners().subscribe(
      ownersList => {
        this.owners = ownersList;
        // console.log("Owner :"+ ownersList[0].pets[0].name);
        console.log("Owner :"+ this.owners[0].pets[0].name);
      });          
  }

You should check once the observable returns a data.

elvis_ferns
  • 524
  • 6
  • 14