gpt4 book ai didi

Angular 2+ 无法读取未定义的属性 'id'

转载 作者:行者123 更新时间:2023-12-02 21:13:39 24 4
gpt4 key购买 nike

我遇到了一个奇怪的错误,但我无法找出原因。根据 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)

如何解决?

详细公告.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>

详细公告.tmp

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);
}

}

最佳答案

您试图在服务器响应之前显示数据,因为您正在对数据发出异步请求。

div 上放置一个 *ngIf 以防止它过早尝试显示数据。

  <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>

关于Angular 2+ 无法读取未定义的属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47501385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com