我是初学者。我无法解决这个问题。我已经阅读了其他错误,但仍然无法理解。
当我正在执行 .map 或 .订阅服务时,它给了我错误,例如类型对象上不存在属性"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() {}
}
这是我的服务:数据大陆服务
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() 方法的响应。
旧的 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]);
}