Home > Software design >  Why I can't reach the properties at Angular?
Why I can't reach the properties at Angular?

Time:02-18

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 }

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

CodePudding user response:

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