Jishad
Jishad

Reputation: 2965

Angular 5 HTTP get response error Property 'body' does not exist on type 'Object'

I am working on Angular 5 with Http.

enter image description here

Getting this error while serve the application..

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/switchMap';

@Component({
 selector: 'app-post-detail',
 templateUrl: './post-detail.component.html',
 styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
 body: string;
 recent: {};
 constructor(
    private route: ActivatedRoute,
    private router: Router,
    private http: HttpClient,
 ) { }

 ngOnInit() {
   let id = this.route.snapshot.paramMap.get('id');
   let userId = this.route.snapshot.paramMap.get('userid');
   this.getUserPosts(userId);
   this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
   .subscribe((data)=>{
    this.body = data.body;
   });
 }
}

I dont know Why I am getting this error and I assign the type as string in the class based on the syntax.

Response of API as below,

enter image description here

Upvotes: 1

Views: 2929

Answers (1)

Sergi Pasoevi
Sergi Pasoevi

Reputation: 2851

(data)=>{
    this.body = data.body;
}

data is not json. You need to run .json() on data. Or you could run map before subscribe:

 this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
   .map(res => res.json())
   .subscribe((data)=>{
      this.body = data.body;
 });

In order to use map, you need to import it:

import 'rxjs/add/operator/map'

See more examples here: https://angular.io/api/http/Http

EDIT:

The response is typed - you need to create an interface for the response:

interface SomeResponse {
  Body: SomeType;
}

And make the request like this:

this.http.get<SomeResponse>'https://jsonplaceholder.typicode.com/posts/'+id)
  .subscribe((data)=>{
    this.body = data.body;
  });

Again, more examples here: https://codingthesmartway.com/angular-4-3-httpclient-accessing-rest-web-services-with-angular/

Upvotes: 1

Related Questions