【问题标题】:Angular2: json does not exist on type objectAngular2:类型对象上不存在json
【发布时间】:2023-03-08 11:15:01
【问题描述】:

我是初学者。我无法解决这个问题。我已经阅读了其他错误,但我仍然无法理解。

当我在执行 .map 或 .subscribe 服务时,它给了我类似 Property 'json' does not exist on type object. 之类的错误。

这是我的:continents.component.ts

import { Component, OnInit } from '@angular/core';  
import { DataContinentsService } from '../../services/dataContinents.service';
import 'rxjs/add/operator/map';  
@Component({  
selector: 'app-continents',  
templateUrl: './continents.component.html',  
styleUrls: ['./continents.component.css'],  
providers: [DataContinentsService]  
})  
export class ContinentsComponent implements OnInit {  
continent: any;  
constructor(private dataContinentService: DataContinentsService) { }  
public getContinentInfo() {  
this.dataContinentService.getContinentDetail()  
.map((response) => response.json())  
.subscribe(res => this.continent = res.json()[0]);  
}  
ngOnInit() {}  
}  

这是我的服务:DataContinentsService

import { Injectable } from '@angular/core';  
import {HttpClientModule, HttpClient} from '@angular/common/http';  
// import 'rxjs/add/operator/map';  
@Injectable()  
export class DataContinentsService {  
constructor(private _http: HttpClient) {}  
public getContinentDetail() {  
const _url = 'http://restcountries.eu/rest/v2/name/india?fulltext=true';  
return this._http.get(_url);  
}  
} 

这是我的模板:continents.component.html

<h1>Continents</h1>  
<h3>Name: {{continent.name}}</h3>  
<h3>Capital: {{continent.capital}}</h3>  
<h3>Currency: {{continent.currencies[0].code}}</h3>  
<button (click)="getContinentInfo()">get details</button>  

【问题讨论】:

  • 如果您使用的是 HttpClient,则不需要 .map((response) =&gt; response.json()) ,这是针对较旧的 Http 类的。在这种情况下,response 将是已解析的 JSON(因此没有 .json() 函数)
  • 好的。谢谢,但它与 .subscribe 相同
  • 您可以尝试在服务函数定义中添加getContinentDetail(): Observable&lt;any&gt;Observable&lt;any&gt; 位会告诉 Typescript 你正在返回一个 Observable

标签: json angular


【解决方案1】:

我猜你一直在阅读一些过时的文档。 旧的 Http 类用于返回具有 json() 方法的响应。

旧的 Http 类已停用,您现在可以正确使用 HttpClient 类。 HttpClient 的 get() 方法返回任何 Observable - 它为您将响应的 json 映射到一个对象。通常,您会指定对象的类型,如下所示:

   this.http.get<SomeObject>(url);

取而代之的是,您只需获得一个对象。 无论哪种情况,返回的对象都没有 json() 方法。

所以,你的服务应该这样做:

public getContinentDetail(): Observable<Continent[]> {  
  const _url = 'http://restcountries.eu/rest/v2/name/india?fulltext=true';  
  return this._http.get<Continent[]>(_url);  
}

你应该订阅这样的东西

this.dataContinentService.getContinentDetail().subscribe(continents: Continent[] => 
  this.continent = continents[0]);  
}  

【讨论】:

  • 我无法理解...我的服务功能现在出现错误。 找不到名称 Continent[]
  • 如果没有,则需要定义一个与 json 响应中的属性匹配的 Continent 类
  • 好的。当然谢谢
猜你喜欢
  • 2017-01-14
  • 2018-02-10
  • 2018-05-13
  • 2019-01-09
  • 2021-09-19
  • 2023-03-26
  • 2016-12-31
  • 2018-07-16
  • 1970-01-01
相关资源
最近更新 更多