【发布时间】:2023-03-08 11:15:01
【问题描述】:
我是初学者。我无法解决这个问题。我已经阅读了其他错误,但我仍然无法理解。
当我在执行 .map 或 .subscribe 服务时,它给了我类似 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>
【问题讨论】:
-
如果您使用的是 HttpClient,则不需要
.map((response) => response.json()),这是针对较旧的Http类的。在这种情况下,response将是已解析的 JSON(因此没有.json()函数) -
好的。谢谢,但它与 .subscribe 相同
-
您可以尝试在服务函数定义中添加
getContinentDetail(): Observable<any>。Observable<any>位会告诉 Typescript 你正在返回一个 Observable