2017-05-15 1 views
0

그래서 Angular 웹 사이트의 문서를 살펴보고 기본 "영웅"앱을 만들었습니다.어떻게이 변수에 액세스 할 수 있습니까? this.hero

출력 변수를 갖고 있기 때문에 입력 변수 영웅에 액세스하려고 시도했지만 오류가 발생합니다.

Error: Uncaught (in promise): TypeError: this.hero is undefined 

이 호출은 내가 충돌과 나에게 그 오류를 제공) (ngOnInit에 전화를 시도하지만 일단, 예를 들어, 다른 방법으로 버튼을 사용하는 동안 호출되는 방법을 사용할 수 있습니다.

여기 내 코드입니다 : 배경 영웅의 속성

this.route.params.switchMap((params: Params) => this.heroService.getHero(+params['id'])).subscribe(hero => this.hero = hero); 
console.log(this.hero.background); 

.

특정 코드가 필요하지 않습니다.이 코드는 튜토리얼에서 다루지 않았으며 어떤 방향을 원합니다.

나는 많은 시간을 들여 검색했지만 항상 실패로 끝납니다. 이제는 내 모든 청력을 찢기 전에 누군가가 나에게 약간의 지침을 줄 수 있습니까?

당함가

import { Component, Input, OnInit } from '@angular/core'; 
import { ActivatedRoute, Params } from '@angular/router'; 
import { Location }     from '@angular/common'; 

import { HeroService } from './hero.service'; 
import { Hero } from './hero'; 

import 'rxjs/add/operator/switchMap'; 

let body = document.getElementsByTagName('body')[0]; 
@Component({ 
    selector: 'hero-detail', 
    templateUrl: './hero-detail.component.html', 
    styleUrls: [ './hero-detail.component.css' ] 
}) 


export class HeroDetailComponent implements OnInit { 
    @Input() hero: Hero; 
    constructor(
    private heroService: HeroService, 
    private route: ActivatedRoute, 
    private location: Location 
) { } 

    oldBody:string = body.style.backgroundImage; 

    ngOnInit(): void { 
    this.route.params.switchMap((params: Params) => this.heroService.getHero(+params['id'])).subscribe(hero => this.hero = hero); 

    console.log(this.hero.background); 
    } 

    ngOnDestroy() { 
     body.style.backgroundImage = this.oldBody; 
    } 

    goBack(): void { 
    this.location.back(); 
    } 

    updateBackground(): void { 
    body.style.backgroundImage = "url('"+this.hero.background+ "')"; 
    } 

    save(): void { 
    this.heroService.update(this.hero) 
    .then(() => this.goBack()); 
    } 
} 
+0

는 로직 단계는 단계가 될 따라와 "이"핵심 단어는 당신이 생각하는 상황에 있는지 확인하십시오. – Bindrid

+0

@Bindrid 내 변수 선언에'@Input() hero : Hero; '가 있는데 this에 액세스하면 this 키워드로 사용됩니까? 내가 아는 다른 방법이 없다는 뜻입니다.이 키워드없이 정규 영웅을 사용하면 인스턴스를 참조하도록 요청하는 오류가 발생합니다. – seeocon

+0

좀 더 코드를 제공해 주시겠습니까? – Tamas

답변

0

관찰 가능한 구독이 실행되기 전에 console.log가 실행되는 것이 문제입니다. 'hero'필드는 구독 콜백이 실제로 실행될 때까지 정의되지 않습니다.

이 같은 가입에 콘솔 로그를 이동해야합니다

this.route.params.switchMap((params: Params) => 
    this.heroService.getHero(+params['id']) 
).subscribe(hero => { 
    this.hero = hero; 
    console.log(this.hero.background); 
}); 
+0

하하 와우, 피드백에 대한 감사, 빠른했습니다. 나는 모두가 어딘가에서 시작해야한다고 생각한다. 변경 사항을 더 잘 이해하려면 다음을 수행하십시오. 내가 뭘하고 있었는지는 엄격하게 변수를 정의하는 것이었지만 ** ngOnInit **는 실제로 변수를 초기화하지 못했습니다. 블록을 작성하여 변수가 초기화되도록합니다. – seeocon

+0

블록 (중괄호 추가)을 변경하면 여러 명령문을 쓸 수 있다는 점만 제외하면 아무 것도 변경되지 않습니다. (컨벤션으로 나는 단지 하나의 명령문 일지라도 구독 콜백에서 항상 중괄호를 사용한다.) 명확하게 생각한다.) 어쨌든 'subscribe'함수의 코드는 getHero()가 완료된 후 비동기 적으로 실행된다. 그러나 이전에 console.log가 있던 subscribe 콜백 외부의 코드는 동 기적으로 실행됩니다. – dbandstra

0

구성 요소를 사용할 때 실제로 Input()로 영웅을 제공하는 것입니다, 그래서 여기에 코드를 요청? 당신이 당신의 구성 요소의 Input으로 hero를 정의하고 있기 때문에

export class HeroDetailComponent implements OnInit { 
    public hero: Hero 
// rest of your code 
+0

예를 들었지만 미니 응용 프로그램에서 작업을 시작할 때 사용을 중단했습니다. 이전에 공개로 변경해 보았지만 여전히 작동하지 않았습니다. : \ – seeocon

+0

아주 간단한/기본 구성 요소를 생각해 내면 어떻게됩니까?뭔가 수출 클래스 TestComponent 같은 구현 OnInit {공공 메시지; ngOnInit() this.message = 'hello'; } 이것은 단지 작동해야합니다. – Tamas

0

, 당신은 아래처럼 parentComponent에에서 직접 설정 할 수 있습니다 : 그렇게하지 않으면, 여러분의 코드는 바로 읽어야

<hero-detail [hero]="selectedHero"></hero-detail> // here selectedHero is what you selected from ParenComponent 

과에 따라 당신이 직면하고있는 오류 (this.hero is undefined), 당신은 위의 일을하지 않았기 때문에 this.heroService.getHero에서 데이터를 얻을 때까지 @Input() hero은 아직 정의되지 않았습니다.

비동기 호출이기 때문에 console.logsubscribethis.heroService.getHero으로 옮기기 만하면됩니다.

관련 문제