我收到了 ERROR TypeError:无法读取属性' id'当我导航到我的组件时未定义调试我的代码后,我发现我的错误在哪里,但我找不到合适的解决方法。也许你可以帮助我?
下面是我的.ts文件:
@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);
}
及其相应的.html文件:
<div *ngIf="theme">
<h2>{{ theme.name | uppercase }}</h2>
<table class="Threads">
<tr>
<th>Id</th>
<th>Date</th>
<th>Title</th>
<th>Views</th>
<th>Thanks</th>
<th>Comments</th>
</tr>
<tr *ngFor="let thread of threads | async">
<a routerLink="/forum-message/{{theme._id}}/{{thread._id}}">
<td><span class="badge">{{thread._id}}</span></td>
</a>
<td>{{thread.createdAt | date}}</td>
<td>{{thread.title}}</td>
<td>{{thread.numberOfViews}}</td>
<td>{{thread.numberOfThanks}}</td>
<td>{{thread.numberOfComments}}</td>
</tr>
</table>
</div>
我试图再次调用路线快照,它有效.. 但我不喜欢两次调用路径快照的事实,所以可能还有另一种方式吗?
getThreads(): void {
this.threads = this.threadService.getThreads(
this.route.snapshot.paramMap.get('theme'));
}
提前感谢您的帮助!
答案 0 :(得分:0)
在ngOnInit
块中,您正在异步运行两个函数,因此theme
中的getThreads
查找将是未定义的。您需要等到主题设置完毕。
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);
}
答案 1 :(得分:0)
在调用我的函数之前,我终于更改了我的代码this.route.snapshot.paramMap.get('theme');
const
:
ngOnInit() {
const id = this.route.snapshot.paramMap.get('theme');
this.themeService.getTheme(id)
.subscribe(theme => {
this.theme = theme,
this.getThreadsTheme(theme._id)
});
}