我是angular8的新手。
我正在编写一个读取简单服务的组件。在使用VScode编写代码的过程中,没有错误被触发,而当我为应用程序提供服务时,出现此错误:
错误TypeError:无法读取未定义的属性'getItalyWeatherData'
这是我的服务
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class WeatherForecastApiService {
constructor(private http: HttpClient) { }
public getItalyWeatherData(cityName: string) {
const s = 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + ',it&appid=d5754a8efdf1ead276cffa4f8250f1e1';
return this.http.get(s);
}
}
这是我的组件:
.ts
文件
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { WeatherForecastApiService } from './weatherForecastApiService/weather-forecast-api.service';
@Component({
selector: 'app-weather-forecast',
templateUrl: './weather-forecast.component.html',
styleUrls: ['./weather-forecast.component.scss'],
})
export class WeatherForecastComponent {
public weatherData: WeatherForecastApiService;
public weatherFeature = new BehaviorSubject<WeatherFeature>(undefined);
constructor() {
this.weatherData.getItalyWeatherData('Pisa').subscribe((response) => {
const ks: string[] = ['name', 'main', 'temp', 'pressure', 'weather'];
this.weatherFeature.next({
cityName: response[ks[0]],
degrees: Number((response[ks[1]][ks[2]] - 273.15).toFixed()),
pressure: Number(response[ks[1]][ks[3]]),
sky: response[ks[4]][0][ks[1]],
});
console.log(this.weatherFeature);
});
}
}
.html
文件:
<div class="weatherForecastSpace"></div>
我希望这没什么严重的,这可能是我最初的缺点。
答案 0 :(得分:2)
该服务需要注入未定义为类属性的组件中。
constructor(public weatherData: WeatherForecastApiService) {
// you code
}