为什么我无法到达 Angular 的房产?

Why I can't reach the properties at Angular?

我正在使用一项服务从后端获取数据。 控制器工作正常。 我可以在 Angular GUI 上显示接收到的对象。

<p> {{feedback | json}} </p>

输出如下所示:

{ "id": 1, "comment": "Erster Eintrag, interessant.", "userId": 1012, "subject": "Mein Eintrag", "up": 22, “下”:2}

但是当我尝试访问此接收对象的单个 属性 时:

<p>Id: {{feedback.id}}</p>

比我得到一个错误:

我需要更改什么才能访问所有属性并在 GUI 上显示它们?

我的代码片段:

export class CommentListComponent implements OnInit {

  feedbackIdAsString: string = '';
  feedbackId = 0;
  feedback: Feedback | undefined ;
  feedbacks: Feedback[] = [];
  comment_list: Comment[] = [];

  constructor(
    private route: ActivatedRoute,
    private feedbackService: FeedbackService,
    private commentListService: CommentListService) { }

  ngOnInit(): void {
    this.feedbackIdAsString = this.route.snapshot.paramMap.get('feedbackId') ?? '';
    this.feedbackId = +this.feedbackIdAsString;    this.feedbackService
      .getFeedback(this.feedbackId)
      .subscribe(feedback => this.feedback = feedback);

    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => this.feedbacks = feedbacks);

    this.commentListService
      .getComments()
      .subscribe(commentlist => this.comment_list = commentlist);
  }
}

export class FeedbackService {

  public myUrl: string = "https://localhost:7235/feedback";

  constructor(private http: HttpClient) { }

  getFeedbacks(): Observable<Feedback[]> {
    let result: Observable<Feedback[]>;
    result = this.http.get<Feedback[]>(this.myUrl);
    return result;
  }

  getFeedback(id: number): Observable<Feedback> {
    let result: Observable<Feedback>;
    let urlSingleFeedback = this.myUrl + '/' + id;
    result = this.http.get<Feedback>(urlSingleFeedback);
    return result;
  }
}

属性 feedback 在渲染模板时仍然未定义,因为 getFeedbacks 很可能是异步的。您可以输入 ngIf 或使用 .?

<p>Id: {{feedback?.id}}</p>
<p *ngIf="feedback?.id">Id: {{feedback.id}}</p>