Angular 错误类型错误:无法读取属性';id';未定义的
我遇到一个错误TypeError:当我导航到我的组件时,无法读取未定义的属性“id”。调试完代码后,我发现错误在哪里,但我没有找到合适的方法来解决它。也许你能帮我 下面是my.ts文件:Angular 错误类型错误:无法读取属性';id';未定义的,angular,rxjs,Angular,Rxjs,我遇到一个错误TypeError:当我导航到我的组件时,无法读取未定义的属性“id”。调试完代码后,我发现错误在哪里,但我没有找到合适的方法来解决它。也许你能帮我 下面是my.ts文件: @Component({ selector: 'app-forum-thread', templateUrl: './forum-thread.component.html', styleUrls: ['./forum-thread.component.css'] }) export class F
@Component({
selector: 'app-forum-thread',
templateUrl: './forum-thread.component.html',
styleUrls: ['./forum-thread.component.css']
})
export class ForumThreadComponent implements OnInit {
@Input() theme: Theme;
threads: Observable<Thread[]>;
constructor(
private route: ActivatedRoute,
private location: Location,
private themeService: ThemeService,
private threadService: ThreadService
) { }
ngOnInit() {
this.getTheme();
this.getThreads();
}
getTheme(): void {
this.themeService.getTheme(this.route.snapshot.paramMap.get('theme'))
.subscribe(theme => this.theme = theme);
}
// Error caused by this method..
getThreads(): void {
this.threads = this.threadService.getThreads(this.theme.id);
}
提前感谢您的帮助 在
ngOnInit
块中,您正在异步运行两个函数,因此getThreads
中的theme
查找将是未定义的。您需要等待主题设置完成
getTheme(): void {
this.themeService.getTheme(this.route.snapshot.paramMap.get('theme'))
.subscribe(theme => {
this.theme = theme;
this.getThreads(theme.id);
});
}
并将getThreads
更改为:
getThreads(themeId): void {
this.threads = this.threadService.getThreads(themeId);
}
我终于改变了我的代码,把
这个.route.snapshot.paramMap.get('theme')在调用my函数之前的常量中的code>,如下所示:
ngOnInit() {
const id = this.route.snapshot.paramMap.get('theme');
this.themeService.getTheme(id)
.subscribe(theme => {
this.theme = theme,
this.getThreadsTheme(theme._id)
});
}
我更改了gethreads()
以获取subscribe-in参数的主题,并且没有得到错误类型ERROR:无法再读取未定义消息的属性“id”,但我得到了这个get 500(内部服务器错误)。似乎在调用函数之前没有完成定义。我更新了答案,将线程id作为param接受,而不是在类上查找。
getThreads(themeId): void {
this.threads = this.threadService.getThreads(themeId);
}
ngOnInit() {
const id = this.route.snapshot.paramMap.get('theme');
this.themeService.getTheme(id)
.subscribe(theme => {
this.theme = theme,
this.getThreadsTheme(theme._id)
});
}