gpt4 book ai didi

javascript - 尝试使用 Angular 创建数据时出现错误

转载 作者:行者123 更新时间:2023-12-01 00:33:08 25 4
gpt4 key购买 nike

我正在尝试使用 Http 库中的 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 );
})
}

最佳答案

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

所以,你可以直接设置post.id = response.id,因为response已经是一个有效的解析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
})
}
}

关于javascript - 尝试使用 Angular 创建数据时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58346695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com