【问题标题】:Property 'json' does not exist on type 'Object'.ts(2339)类型“对象”.ts(2339) 上不存在属性“json”
【发布时间】:2021-09-19 00:03:04
【问题描述】:

我正在构建一个 MEAN Stack 消息传递应用程序。我正在尝试从我的后端检索响应,但收到以下错误:

“类型'Object'.ts(2339)上不存在属性'json'”

以下代码中的问题是 res.json() 的 'json' 部分

import { HttpClient } from "@angular/common/http";
import {Injectable} from '@angular/core';
import { HttpClient } from "@angular/common/http";
import {Injectable} from '@angular/core';

@Injectable()
export class ApiService  {
    constructor (private httpClient : HttpClient ){}

    messages = []
    getMessage(){
        this.httpClient.get('http://localhost:3000/posts').subscribe(res =>{
        //FIX AT LATER STAGE should be this.messages = res.json()
        this.messages = res.json();
        })
    }

}

【问题讨论】:

  • HttpClient 自动将结果解析为 JSON。您不需要对响应执行 json 方法。如果你记录 console.log(res) 会发生什么?

标签: node.js json angular typescript mean-stack


【解决方案1】:

下面是 Angular 的情况:

HttpModule (*)

import { HttpModule, Http } from '@angular/http';
  • 旧的和已弃用的
  • JSON 响应需要手动解析:res.json()

HttpClientModule (Angular 4.3+)

import { HttpClientModule, HttpClient } from '@angular/common/http';
  • 当前 (LTS)
  • JSON 响应已被解析。 res.json() 不是必需的。

* 我可能对版本号有点不满意。请查看changelog

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2021-01-10
    • 2019-08-11
    • 2021-08-02
    • 2020-06-02
    • 2022-07-09
    • 2022-10-04
    • 2023-02-07
    • 2020-08-23
    相关资源
    最近更新 更多