因此,我浏览了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”关键字使用吗?我的意思是我没有其他方式,我知道 - 如果我使用没有这个关键字的普通英雄,它会给我一个错误,要求我引用该实例。 – seeocon
你能提供更多的代码吗? – Tamas