skip to Main Content

Although the app works fine despite the error, I am receiving that error in my console because my component has not loaded the ‘post’ observable from the backend through the postService. My code is:

Component

export class PostComponent {
  post!: Post;

  constructor(
    activatedRoute: ActivatedRoute,
    private postService: PostService,
    private timeFormatService: TimeFormatService
  ) {
    activatedRoute.params.subscribe((params) => {
      if (params['id'])
        postService.getPostById(params['id']).subscribe((serverPost) => {
          this.post = serverPost;
        });
    });
  }
}

My html just displays post values such as {{post.owner}} or {{post.title}} in paragraphs or headings.

Im getting that error for each post value.
Ive figured i can fix this error by setting default values by changing post!:Post; to:

post:Post = {owner: '', title: ''}

And when the postService gets the real post details from the backend it updates the values. Im sort of new to coding, is this the correct way to do it?

2

Answers


  1. Make it async.

    post$ = this.activatedRoute.params.pipe(
      map(params => params.id),
      filter(Boolean), 
      switchMap(this.postService.getPostById.bind(this.postService))
    );
    
    <ng-container *ngIf="post$ | async as post">
      {{post.title}}
    </ng-container>
    
    Login or Signup to reply.
  2. You can use {{post?.title}} to keep element in DOM and show the value as soon as you have it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search