首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2: json在类型对象上不存在

Angular2: json在类型对象上不存在
EN

Stack Overflow用户
提问于 2018-05-06 22:07:51
回答 1查看 845关注 0票数 1

我是初学者。我解决不了这个问题。我已经读过其他的错误,但是我还是不能理解。

当我对服务执行.map或.subscribe时,会产生错误,就像属性'json‘在对象类型上不存在一样。

这是我的: continents.component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
<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>  
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-06 22:19:55

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

旧的Http类已经退役,现在您正在正确地使用HttpClient类。HttpClient的get()方法返回一个可观察的任意值-它将响应的json映射到对象。通常,您会指定对象的类型,如下所示:

代码语言:javascript
复制
   this.http.get<SomeObject>(url);

取而代之的是,你只得到了一个物体。在这两种情况下,返回的对象上都没有json()方法。

因此,您的服务应该这样做:

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

你应该订阅这样的东西

代码语言:javascript
复制
this.dataContinentService.getContinentDetail().subscribe(continents: Continent[] => 
  this.continent = continents[0]);  
}  
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50204981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档