【问题标题】:Angular Uncaught Error: Can't resolve all parameters for service角度未捕获错误:无法解析服务的所有参数
【发布时间】:2019-04-17 13:23:11
【问题描述】:

我不明白为什么这项服务不起作用?是不是依赖有问题?

服务:

import { Http } from '@angular/http';

export class GetWeatherService {

    constructor(private http: Http) {}

    getWeather() {
        return this.http.get(link);
    }
}

和组件:

import { Component, OnInit } from '@angular/core';
import { GetWeatherService } from './get-weather.service';

@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.css'],
    providers: [GetWeatherService]
})
export class FormComponent implements OnInit {

    constructor(public getWeather: GetWeatherService) {}

    ngOnInit() {
        this.getWeather.getWeather();
    }
}

【问题讨论】:

  • hagner 的答案是您所需要的,但我也可以建议使用新的 HttpClient 而不是“Http”。它有许多改进:-)

标签: angular typescript


【解决方案1】:

您需要使您的服务可注入:

@Injectable()
export class GetWeatherService {
    //CODE
}

【讨论】:

  • 当我想从另一个服务注入对这个服务的依赖时,我以为我正在添加 Injectable 装饰器。非常感谢。有用。问候
【解决方案2】:

在你的服务上添加@Injectable(),让它注入到构造函数中。

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';

@Injectable()
export class GetWeatherService {

    constructor(private http: Http) {}

    getWeather() {
        return this.http.get(link);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2018-12-18
    • 2018-09-21
    • 2023-03-16
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多