Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I can't reach the properties at Angular?

I’m using a service to get data from backend.
The Controller is working fine.
And I can show the received object at the Angular GUI.

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

The output looks like this:

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when I try to access a single property of this received object:

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

Than I get a error:
enter image description here

What I need to change to access all the properties and to show them at the GUI?

My code snippets:

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

>Solution :

The property feedback is still undefined when rendering the template, because the getFeedbacks is most likely async. You can either put an ngIf or use .?

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading