그래서 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());
}
}
는 로직 단계는 단계가 될 따라와 "이"핵심 단어는 당신이 생각하는 상황에 있는지 확인하십시오. – Bindrid
@Bindrid 내 변수 선언에'@Input() hero : Hero; '가 있는데 this에 액세스하면 this 키워드로 사용됩니까? 내가 아는 다른 방법이 없다는 뜻입니다.이 키워드없이 정규 영웅을 사용하면 인스턴스를 참조하도록 요청하는 오류가 발생합니다. – seeocon
좀 더 코드를 제공해 주시겠습니까? – Tamas