0

post-detail.component.ts:

import { Component, OnInit } from '@angular/core';
import { Post } from '../../models/post';
import { ActivatedRoute } from '@angular/router';
import { PostService } from '../../services/post.service';
@Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
  post: Post;

  constructor(private route: ActivatedRoute,
              private postService: PostService) { }
  ngOnInit() {
    var id: string = this.route.snapshot.params["id"]
    this.postService.searchPost(id).subscribe((post) => {
      this.post = post;
    });
  }
}

post-detail.component.html:

<div class="row">
  <div class="col-xs-12">
    <img 
      src="{{ post.image }}" 
      alt="{{ post.title }}" 
      class="img-responsive"
      style="max-width: 470px">
  </div>
</div>
<div class="row">
  <div class="col-xs-12">
    <h2>{{ post.title }}</h2>
  </div>
</div>
<div class="row">
  <div class="col-xs-12">
    {{ post.text }}
  </div>
</div>

post.service.ts:

import { Post } from '../models/post';
import { Http } from '@angular/http'
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';

@Injectable()
export class PostService {  

constructor(private http: Http) { }

  searchPost(id): Observable<Post> {    
    return this.http
      .get("http://localhost:8080/posts/" + id)
      .map(res => res.json())
      .map(res => <Post>res.post);
  }
}

These are the errors im getting

Browser screenshot with rendered template and errors

So, I'm being told by Chrome that the object I'm trying to use in the template is undefined, although everything is obviously defined if you look at the rendered view. After a some research, I gained insight on the problem while reading to this StackOverflow thread.

My best guess is that, since postService.searchPost(id) is an asynchronous method, angular will get the data after rendering the view, which is why I get those initial errors.

I've been trying to search for some way to delay the view rendering until the data is retrieved from the service but have not been successful. How can I get rid of these errors?

2
  • initialize your object or use safe navigation operator or use *ngIf Commented Dec 19, 2017 at 6:50
  • Just to add to the above, the safe navigation operator approach would look like this: {{ post?.text }} Simply adding the question mark ensures that the binding is not evaluated until post has a value. Commented Dec 19, 2017 at 7:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.