0

I am trying create a new post using the post method in Http library. I have an input box in the template and if anyone add a post through that input box will that post in the list.

But I am getting an error in post.id=response.json().id. Please find the code below.

posts:any[];
private url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http : HttpClient) {
http.get(this.url).subscribe( (Response: any[]) => {
this.posts = Response;
} )
}
addPost(postTitle:HTMLInputElement){
let post:any = {input : postTitle.value}
postTitle.value = '';
this.http.post(this.url, JSON.stringify(post))
.subscribe( response => {
post.id = response.json().id;
this.posts.splice(0, 0, post)
//console.log( response );
})
}
1
  • Yes, it is returning an object with id and I want to show that particular post with that id. Commented Oct 11, 2019 at 18:44

3 Answers 3

1

unlike the old HttpModule, the HttpClientModule provides the json response back

so, you can directly set post.id = response.id since response is already a valid parsed json

Update

See working code below : https://stackblitz.com/edit/angular-5tmcvj?embed=1&file=src/app/hello.component.ts

import { Component, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'hello',
  template: `
  <input type="text" (keyup.enter)="addPost(input)" #input placeholder="Enter Post Here......." class="form-control">
    <ul class="list-group mt-3">
      <li class="list-group-item" *ngFor="let post of posts | slice:0:8">{{ post.title }}</li>
    </ul>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  posts: any[];
  private url = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) {
    http.get(this.url)
    .subscribe( (response: any[]) => {
      this.posts = response;
    })
  }

  addPost(input: HTMLInputElement){
    let post:any = {
      title: input.value
    } // since post should be an object and you are displaying post.title in the list
    this.http.post(this.url, JSON.stringify(post))
      .subscribe( (data:any) => {
        console.log(data);
        post.id = data.id;
        this.posts = [post,...this.posts]; // adds the new post to the top of this.posts so that the slice(0,8) will contain the updated value
      })
  }
}
Sign up to request clarification or add additional context in comments.

8 Comments

Getting this error - Property 'id' does not exist on type 'Object'.
console.log(response) and see what the object is and if the response has the id
Getting an object with id:101 {id: 101}
then response.id should be available too!
Please check the link - stackblitz.com/edit/angular-fn8rtd?embed=1&file=src/app/…. If i try to add a title by typing the name in the input box that title should appear in the top of the list. When typing something and pressing enter see the console.
|
1

The error is being caused by json() specifically. json() is something that you would usually do with fetch() to parse an application/json body. You wouldn't need to do this with HttpClient as it automatically parses JSON for you. Try changing:

post.id = response.json().id

To just:

post.id = response.id

Update:

You are indicating an error of Property 'id' does not exist on type 'Object'.. This is happening because you are not providing a type for the response and TypeScript does not know what properties exist on the resolved payload. You can get around this by doing:

post.id = response['id']
// or
// post.id = (response as any).id

That being said, instead you should make an interface or class that represents the structure of your payload and provide that to the HttpClient call.

interface MyInterface {
  id: number;
}

// ...

this.http.post<MyInterface>(this.url, JSON.stringify(post))
  .subscribe(response => {
    post.id = response.id;
    // ...
  });

Hopefully that helps!

7 Comments

Thank you for your reply. While making the change getting this error. Property 'id' does not exist on type 'Object'.
@RAHULKUNDU I updated an answer to help with the Property 'id' does not exist on type 'Object'. error.
now its showing - Cannot create property 'id' on string 'sasas'
I don’t know what sasas is. Is that something returned from your server? Is that something from another component in this Angular app? You need to provide more information. The answer above resolves the specific Angular/TypeScript issue you described.
Basically, I have a input box and a list of titles getting from jsonplaceholder.typicode.com/posts. I am getting this titles using get method of http. Now if i type something in the input box and press enter I want that title to add on top that list of titles. When i am typing a text in the box and pressing enter it is showing Cannot create property 'id' on string 'new title'. In this method I am using post method.
|
0

HttpClient always provides json object as a response so no need to use ".json()" method to parse it again. Just use:

post.id = response.id;

1 Comment

Please check the link - stackblitz.com/edit/… If i try to add a title by typing the name in the input box that title should appear in the top of the list. When typing something and pressing enter see the console

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.