Angular 2 - 无法读取未定义

时间:2017-10-05 23:09:05

标签: javascript angular angular-http

Angular很新。我检查了类似的问题,但他们要么深入研究细节,要么我不理解解决方案。

实际错误: “无法在Object.eval中读取未定义的属性'idPlanet'[作为updateRenderer](PlanetComponent.html:11)”

问题: planetDetail.idPlanet最有可能是未定义的?

可疑: getPlanetDetail()

planet.component.html:

<div class="col-sm-9">
  ID: {{ planetDetail.idPlanet }}
</div>

planet.component.ts:

import {
  Component,
  OnInit
} from '@angular/core';

import { Planet }               from './planet';
import { PlanetService }        from './planet.service';

@Component({
  selector: 'planets',
  templateUrl: './planet.component.html'
})
export class PlanetComponent implements OnInit {

    private planets: Planet[];
    private planetDetail: Planet;
    constructor(
        private planetService: PlanetService
    ) {}

    public ngOnInit(): void {
      this.getPlanetDetail();
      this.getPlanets();
    }

    public getPlanets() {
      this.planetService.getPlanets()
          .subscribe(
              (planets) => this.planets = planets
          );
    }

    public getPlanetDetail() {
      this.planetService.getPlanetDetail()
          .subscribe(
              (planets) => this.planetDetail = planets
          );
    }

}

planet.service.ts:

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { Planet } from './planet';

@Injectable()
export class PlanetService {

    private planetsUrl = 'http://localhost/index.php/api/planet/';  // URL to web api

    // Injecting the http client into the service
    constructor(private http: Http) {}

    public getPlanets(): Observable<Planet[]> {
        return this.http.get(this.planetsUrl + 'planets/id_sol/1')
            .map(this.parseData)
            .catch(this.handleError);
    }

    public getPlanetDetail(): Observable<Planet> {
      return this.http.get(this.planetsUrl + 'planet/id_planet/1')
          .map(this.parseData)
          .catch(this.handleError);
    }

    private parseData(res: Response) {
        let body = res.json();

        if (body instanceof Array) {
            return body || [];
        } else {
            return body.post || {};
        }
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

我很茫然,我试图从getPlanets()构建我的getPlanetDetail()方法,但是工作正常。我应该使用承诺吗?

我很难搞清楚我可以将console.log()放到哪里进行调试。我正在使用Github的角度入门套件。

感谢您的时间。

编辑1:api输出{“idPlanet”:“1”,“name”:“Earth”}

3 个答案:

答案 0 :(得分:2)

由于请求是异步的,有时在页面加载时不会从服务器获取值,因此,planetDetail是未定义的。为了避免这种情况,你可以使用add&#39;?&#39;在planetDetail和idPlanet之间。仅在具有值

时打印

ID: {{ planetDetail?.idPlanet }}

如果要打印结果或错误 public getPlanetDetail() { this.planetService.getPlanetDetail() .subscribe( (planets) => { console.log(planets); this.planetDetail = planets }, error => {console.log(error);} ); }

答案 1 :(得分:1)

我的朋友要调试你的&#39; planetDetail&#39;填充,只需添加&#39; console.log(planetDetail)&#39;在&#39;订阅&#39;方法。请按照以下示例。

public getPlanetDetail() {
  this.planetService.getPlanetDetail()
      .subscribe(
          (planets) => this.planetDetail = planets
      );
}

public getPlanetDetail() {
  this.planetService.getPlanetDetail()
      .subscribe(
          (planets) => this.planetDetail = planets, (err) => (err), () => console.log(this.palnetDetail)
      );
}

有关subscribe()的更多信息

&#13;
&#13;
subscribe(function(response) {
  console.log("Success Response" + response)
},
  function(error) {
  console.log("Error happened" + error)
},
  function() {
  console.log("the subscription is completed")
}); 
&#13;
&#13;
&#13;

答案 2 :(得分:1)

由于您的回复是 Parse error: syntax error, unexpected '$current_username' (T_VARIABLE) in {file directory} on line 18 ,请尝试以下操作:

{"idPlanet":"1","name":"Earth"}