操作服务响应但返回undefined

时间:2017-02-08 22:00:23

标签: json angular angular-services

模型组件:

import { Component, OnInit, AfterContentInit } from '@angular/core';
import { Model } from '../model';
import { EdmundsAPIService } from '../edmunds-api.service';
import {  ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-models',
  templateUrl: './models.component.html',
  styleUrls: ['./models.component.css']
})
export class ModelsComponent implements OnInit, AfterContentInit {
public models: Model[];
errorMessage: string;

  constructor(private route: ActivatedRoute,
              private _EdmundsAPIService: EdmundsAPIService) {}

  getModels(): void {
    this._EdmundsAPIService.getModels(this.route.snapshot.params[ 'data' ])
      .subscribe(
       models => this.models = models,
       error =>  this.errorMessage = <any>error);
     }

  ngOnInit() {
    this.getModels();
    console.log(this.models);
  }

EdmundsAPIService:

  getModels(makeNiceName: number): Observable<Model[]> {
    return this.http.get('REDACTED')
    .map(res => res.json())
    .catch(this.handleError);
  }

我正在尝试访问这个。模型&#39;在我的ngOnInit(或其他生命周期钩子)中,以便对我的JSON响应进行排序和过滤。不过,我的console.log会返回undefined

2 个答案:

答案 0 :(得分:1)

这是一个异步调用,当您尝试console.log结果时,尚未检索到数据。

  ngOnInit() {
    this.getModels(); // executing
    // logging before above function has finished executing
    console.log(this.models);
  }

如果您要在订阅中移动console.log,那么您可以确定自己拥有以下值:

  getModels(): void {
    this._EdmundsAPIService.getModels(this.route.snapshot.params[ 'data' ])
      .subscribe(
       models =>  {
         this.models = models; // values set
         console.log(this.models); // values available!
       });
     }

答案 1 :(得分:1)

getModels(): void {
    this._EdmundsAPIService.getModels(this.route.snapshot.params[ 'data' ])
      .subscribe(
           (models: Model[]) => { 
               this.models = models

               //THIS IS WHERE YOU MANIPULATE YOUR DATA
               console.log(this.models) // IF SERVICE IS WORKING THIS WILL NOT BE UNDEFINED
           },
           (error: any) =>  this.errorMessage = error 
      );
 }