组件无法读取服务(带有linter的VScode没有注意到任何内容)

时间:2019-11-11 08:39:49

标签: angular typescript visual-studio-code angular8

我是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>

我希望这没什么严重的,这可能是我最初的缺点。

1 个答案:

答案 0 :(得分:2)

该服务需要注入未定义为类属性的组件中。

constructor(public weatherData: WeatherForecastApiService) {
       // you code
}

在这里阅读:https://angular.io/guide/dependency-injection