猿问

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

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

})

}



心有法竹
浏览 133回答 3
3回答

拉风的咖菲猫

与旧的不同HttpModule,它HttpClientModule提供了 json 响应所以,你可以直接设置,post.id = response.id因为响应已经是一个有效的解析json更新请参阅下面的工作代码:https : //stackblitz.com/edit/angular-5tmcvj?embed=1&file=src/app/hello.component.tsimport { Component, Input } from '@angular/core';import { HttpClient } from '@angular/common/http';@Component({&nbsp; selector: 'hello',&nbsp; template: `&nbsp; <input type="text" (keyup.enter)="addPost(input)" #input placeholder="Enter Post Here......." class="form-control">&nbsp; &nbsp; <ul class="list-group mt-3">&nbsp; &nbsp; &nbsp; <li class="list-group-item" *ngFor="let post of posts | slice:0:8">{{ post.title }}</li>&nbsp; &nbsp; </ul>`,&nbsp; styles: [`h1 { font-family: Lato; }`]})export class HelloComponent&nbsp; {&nbsp; posts: any[];&nbsp; private url = 'https://jsonplaceholder.typicode.com/posts';&nbsp; constructor(private http: HttpClient) {&nbsp; &nbsp; http.get(this.url)&nbsp; &nbsp; .subscribe( (response: any[]) => {&nbsp; &nbsp; &nbsp; this.posts = response;&nbsp; &nbsp; })&nbsp; }&nbsp; addPost(input: HTMLInputElement){&nbsp; &nbsp; let post:any = {&nbsp; &nbsp; &nbsp; title: input.value&nbsp; &nbsp; } // since post should be an object and you are displaying post.title in the list&nbsp; &nbsp; this.http.post(this.url, JSON.stringify(post))&nbsp; &nbsp; &nbsp; .subscribe( (data:any) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; &nbsp; post.id = data.id;&nbsp; &nbsp; &nbsp; &nbsp; 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&nbsp; &nbsp; &nbsp; })&nbsp; }}

陪伴而非守候

该错误是由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 {&nbsp; id: number;}// ...this.http.post<MyInterface>(this.url, JSON.stringify(post))&nbsp; .subscribe(response => {&nbsp; &nbsp; post.id = response.id;&nbsp; &nbsp; // ...&nbsp; });希望这有帮助!

狐的传说

HttpClient 始终提供 json 对象作为响应,因此无需使用“.json()”方法再次解析它。只需使用:post.id&nbsp;=&nbsp;response.id;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答