【问题标题】:Component can't read service (VScode with linter doesn't notice anything)组件无法读取服务(带有 linter 的 VScode 不会注意到任何内容)
【发布时间】:2020-03-06 22:35:36
【问题描述】:

我是 angular8 的新手。
我正在编写一个读取简单服务的组件。在用VScode写代码的过程中没有触发错误,而当我服务应用程序时,出现了这个错误:

错误类型错误:无法读取未定义的属性“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>

我希望没什么大不了的,这可能是我最初的缺点。

【问题讨论】:

    标签: angular typescript visual-studio-code angular8


    【解决方案1】:

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

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

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

    【讨论】:

    • 只是添加到关于 VS Code linter 的答案并没有注意到任何事情。添加此标志“严格”:true。
    • 在compilerOptions下的tsconfig.json中
    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多