私は初心者です。私はこの問題を解決することができません。私は他のエラーを読みましたが、それでも理解できません。
サービスに.mapまたは.subscribeを実行しているときに、プロパティ '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>
あなたは古いドキュメントを読んでいると思います。json()メソッドを持っていた応答を返すために使用された古いHttpクラス。
古い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]);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加