【问题标题】:How to access the ID without using json(), while using HttpClient如何在不使用 json() 的情况下访问 ID,同时使用 HttpClient
【发布时间】:2020-10-13 00:03:51
【问题描述】:

我需要在这里访问对象的 id。但是,不能使用 json(),因为它在 HttpClient 中。请指教,有什么解决办法。我面临的错误是:“TS2339:‘对象’类型上不存在属性‘json’。” 如果没有 Json,错误在于“id”。即“TS2339:‘对象’类型上不存在属性‘id’。” (请参考:post['id'] = response.json().id;)

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';
// const headers = { 'Content-Type': 'application/json' };
@Component({
  selector: 'posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css'],
})
export class PostsComponent {
  posts: any[];
  private url = 'https://jsonplaceholder.typicode.com/posts';
  constructor(private http: HttpClient) {
    http
      .get(this.url) //{ headers }
      .subscribe((response: any[]) => {
        this.posts = response;
      });
  }
  createPost(input: HTMLInputElement) {
    let post = { title: input.value };
    this.http.post(this.url, JSON.stringify(post)).subscribe((response) => {
      post['id'] = response.json().id;
      console.log(response);
    });
  }
}

    

【问题讨论】:

    标签: json angularjs angular http


    【解决方案1】:

    试试下面的方法:

    createPost(input: HTMLInputElement) {
        let post = { title: input.value };
        this.http.post(this.url, JSON.stringify(post)).subscribe((response:any) => {
          post['id'] = response.id;
          console.log(response);
        });
      }
    

    看看这个样本:

    https://stackblitz.com/edit/angular-ivy-o8b7ri?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

      猜你喜欢
      • 2017-04-27
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多