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
})
}
}
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;
// ...
});
希望这有帮助!
TA贡献1804条经验 获得超3个赞
HttpClient 始终提供 json 对象作为响应,因此无需使用“.json()”方法再次解析它。只需使用:
post.id = response.id;
添加回答
举报