DRNR
DRNR

Reputation: 453

Response from http-request not showing in template

I am learning http. I follow tutorial from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html but I can't get my data from response. I have no error. I use JSON typicode json: https://jsonplaceholder.typicode.com/posts

Here my code, same from tutorial, cant find error in my code. Can someone help?

Service

  private postsUrl = 'https://jsonplaceholder.typicode.com/posts'

  getPosts(): Promise<Post[]> {
    return this.http.get(this.postsUrl)
      .toPromise()
      .then(response => response.json().data as Post[])
      .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  } 

Class

export class Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

component

@Component({
  selector: 'my-app',
  template: `

  <div *ngFor="let post of posts">
    {{post.title}}
  </div>



  `,
})
export class App implements OnInit {

  posts: Post[] = [];

  constructor(private postsService: PostsService) { }

  ngOnInit(): void {
    this.postsService.getPosts() 
      .then(posts => this.posts = posts)
  }

}

I have plunker: https://plnkr.co/edit/eEj7vPwf3KjlLkdjAisE?p=preview

Thank you in advance for assistance.

Upvotes: 2

Views: 509

Answers (1)

eko
eko

Reputation: 40647

Your response does not have a data field.

So remove .data from

.then(response => response.json().data

Fixed plunker: https://plnkr.co/edit/9bjXi4qhMYlcla9B4nFP?p=preview

Upvotes: 2

Related Questions