我有一个奇怪的错误,我找不到原因。根据route的:id,我得到了表privateLessons,接下来搜索具有正确ID的那个对象并将其显示在我的模板中。最后,我得到了想要的效果,数据可以正确显示,但是在控制台中出现两个相同的错误:
ERROR TypeError: Cannot read property 'id' of undefined
at Object.eval [as updateRenderer] (DetailedAnnouncementComponent.html:3)
at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13094)
at checkAndUpdateView (core.es5.js:12241)
at callViewAction (core.es5.js:12601)
at execComponentViewsAction (core.es5.js:12533)
at checkAndUpdateView (core.es5.js:12242)
at callViewAction (core.es5.js:12601)
at execEmbeddedViewsAction (core.es5.js:12559)
at checkAndUpdateView (core.es5.js:12237)
at callViewAction (core.es5.js:12601)
如何解决?
detail-announcement.html
<div class="detailed-announcement">
{{ privateLesson.id }}
{{ privateLesson.subject }}
{{ privateLesson.category }}
{{ privateLesson.price }}
{{ privateLesson.level }}
{{ privateLesson.voivodeship }}
{{ privateLesson.city }}
{{ privateLesson.place }}
{{ privateLesson.description }}
{{ privateLesson.author }}
</div>
详细公告
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PrivateLessonsService } from './../../../../services/private-lessons.service';
import { PrivateLesson } from './../../../../classes/private-lesson';
@Component({
selector: 'app-detailed-announcement',
templateUrl: './detailed-announcement.component.html',
styleUrls: ['./detailed-announcement.component.scss']
})
export class DetailedAnnouncementComponent implements OnInit {
privateLessons: PrivateLesson[];
privateLesson: PrivateLesson;
privateLessonIdFromParams: number;
constructor(
private _privateLessonsService: PrivateLessonsService,
private _activatedRoute: ActivatedRoute
) { }
ngOnInit() {
this._activatedRoute.params.subscribe(params => {
this.privateLessonIdFromParams = params['id'];
});
this._privateLessonsService
.getPrivateLessons()
.subscribe(
responseData => {
this.privateLessons = responseData;
this.privateLesson = this.getDimensionsByFind(this.privateLessons, this.privateLessonIdFromParams);
}
);
}
getDimensionsByFind(array: any[], id: number){
return array.find(x => x.id === id);
}
}
您正在尝试在服务器响应之前显示数据,因为您正在对数据进行异步请求。
穿上*ngIf
,div
以防止它过早显示数据。
<div class="detailed-announcement" *ngIf="privateLesson">
{{ privateLesson.id }}
{{ privateLesson.subject }}
{{ privateLesson.category }}
{{ privateLesson.price }}
{{ privateLesson.level }}
{{ privateLesson.voivodeship }}
{{ privateLesson.city }}
{{ privateLesson.place }}
{{ privateLesson.description }}
{{ privateLesson.author }}
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句