Angular2:类型对象上不存在json [英] Angular2: json does not exist on type object
问题描述
我是初学者.我无法解决此问题.我已经阅读了其他错误,但仍然无法理解.
I am beginner. I am not able to solve this problem. i have read the other errors but still i am not able to understand.
我在执行.map或.subscribe服务时,会给我类似 类型对象上不存在属性'json'的错误.
While i am doing .map or .subscribe to the service it gives me error like 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>
推荐答案
我猜测您正在阅读一些过时的文档. 旧的Http类用于返回确实具有json()方法的响应.
I'm guessing that you've been reading some outdated documentation. The old Http class used to return a response that did have a json() method.
旧的Http类已经淘汰,您现在可以正确使用HttpClient类. HttpClient的get()方法返回任何一个Observable-将响应的json映射为您的对象.通常,您将指定对象的类型,如下所示:
The old Http class has been retired, and you are now properly using the HttpClient class. HttpClient's get() method returns an Observable of any - it maps the response's json to an object for you. Typically, you'd specify the type of the object, like so:
this.http.get<SomeObject>(url);
取而代之的是,您仅获得一个对象. 无论哪种情况,返回的对象都没有json()方法.
In lieu of that, you just get an Object. In either case, there's no json() method on the returned object.
因此,您的服务应执行以下操作:
So, your service should do this:
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]);
}
这篇关于Angular2:类型对象上不存在json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!