在Angular中订阅observable期间获取未定义的值

时间:2018-02-19 15:48:14

标签: angular observable

    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);
      }
 }

在上面的代码中,我得到了正确的值“console.log(”Owner:“+ ownersList [0] .pets [0] .name);”但是在“console.log(”所有者:“+ this.owners [0] .pets [0] .name)行中为所有者获取未定义的值;           }“

我无法弄清楚为什么会如此。请帮我解决上述问题。

1 个答案:

答案 0 :(得分:0)

Observable是异步的。

表达式:console.log("Owner :"+ this.owners[0].pets[0].name); 在调用订阅之前调用相同的tick。 因此,您未定义。

 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);
      });          
  }

一旦observable返回数据,您应该检查。