我是初学者。我无法解决这个问题。我已经阅读了其他错误,但我仍然无法理解。
当我在服务中执行.map或.subscribe时,它会给我一些错误,例如 Property' json'在类型对象上不存在。
这是我的: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>
答案 0 :(得分:1)
我猜你一直在阅读一些过时的文档。 旧的Http类用于返回一个有json()方法的响应。
旧的Http类已经退役,您现在正在使用HttpClient类。 HttpClient的get()方法返回一个Observable of any - 它将响应的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]);
}