2017-10-05 8 views
0

Angular에 새롭게 추가되었습니다. 비슷한 질문을했는데 구체적인 내용을 보거나 해결책을 이해하지 못했습니다.각도 2 - 정의되지 않은 속성 '...'을 읽을 수 없습니다.

실제 오류 : "속성을 판독 할 수 없음 'idPlanet'미정 여기서 updateRenderer가 같은] Object.eval (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); 
    } 
} 

내가 잃어버린 tbh, getPlanetDetail() 메서드를 잘 작동하는 getPlanets() 빌드하려고했습니다. 약속을 사용해야합니까?

정확히 console.log()를 디버그 할 수있는 위치를 파악하는 데 어려움을 겪고 있습니다. Github의 앵글 스타터 키트를 사용하고 있습니다.

감사합니다.

편집 1 : API를 출력 { "idPlanet": "1", "이름": "지구"}

+1

당신이 planetDetail'은'확신하는 경우를 어떤 시점에서 (비동기 적으로) 채워지고,'ID : {{planetDetail? .idPlane t}}' – Phix

+1

이것을 확인하십시오 :'(행성) => this.planetDetail = 행성'. 아마'행성'은 정의되지 않았습니다. 따라서'parseData' 메쏘드 안에서 콘솔을 호출하여 http 호출의 응답을 확인하십시오. –

+0

그래, 거기에 아무것도 넣지 않을 이유가 아무것도 없다. – qwertzman

답변

1

가입, 다음과 같은 시도에 대한 자세한 :

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

요청이 언젠가 값을 서버에서 가져되지 않습니다 비동기으로 페이지가로드 될 때 따라서 planetDetail은 정의되지 않습니다. 이를 피하기 위해 add '?'를 사용할 수 있습니다. planetDetail과 idPlanet 사이. 이 값을 가지고 인쇄 경우에만이 결과 또는 오류를 인쇄하려면

ID: {{ planetDetail?.idPlanet }}

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

1

당신의 'planetDetail'가 채워진 경우 디버깅하는 내 친구를, 단지 'CONSOLE.LOG를 추가 (planetDetail) '을 구독 방법으로 사용합니다. 아래 예를 따르십시오.

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

응답이 {"idPlanet":"1","name":"Earth"}을하기 때문에) (

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

+0

예 비어 있습니다. – qwertzman

+0

그것은 나에게 일어났습니다 : –

+0

매우 편리합니다, – qwertzman

관련 문제