为了账号安全,请及时绑定邮箱和手机立即绑定

尝试使用 Angular 创建数据时出错

尝试使用 Angular 创建数据时出错

心有法竹 2021-11-18 09:35:20
我正在尝试使用库中的post方法创建一个新帖子Http。我input在模板中有一个框,如果有人通过该input框添加帖子,则会将其添加post到列表中。但是我在post.id=response.json().id. 请在下面找到代码。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 );})}
查看完整描述

3 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

与旧的不同HttpModule,它HttpClientModule提供了 json 响应


所以,你可以直接设置,post.id = response.id因为响应已经是一个有效的解析json


更新


请参阅下面的工作代码: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

      })

  }

}


查看完整回答
反对 回复 2021-11-18
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

该错误是由json()特定原因引起的。json()是你通常fetch()用来解析application/json身体的东西。您不需要这样做,HttpClient因为它会自动为您解析 JSON。尝试改变:


post.id = response.json().id

只是:


post.id = response.id

更新:


您表示的错误为Property 'id' does not exist on type 'Object'.。发生这种情况是因为您没有为响应提供类型,并且 TypeScript 不知道解析的负载上存在哪些属性。您可以通过执行以下操作来解决此问题:


post.id = response['id']

// or

// post.id = (response as any).id

话虽如此,您应该创建一个接口或类来表示您的有效负载的结构,并将其提供给 HttpClient 调用。


interface MyInterface {

  id: number;

}


// ...


this.http.post<MyInterface>(this.url, JSON.stringify(post))

  .subscribe(response => {

    post.id = response.id;

    // ...

  });

希望这有帮助!


查看完整回答
反对 回复 2021-11-18
?
狐的传说

TA贡献1804条经验 获得超3个赞

HttpClient 始终提供 json 对象作为响应,因此无需使用“.json()”方法再次解析它。只需使用:

post.id = response.id;


查看完整回答
反对 回复 2021-11-18
  • 3 回答
  • 0 关注
  • 132 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信