我不明白为什么这项服务不起作用?这是依赖关系的一些问题吗?
服务:
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();
}
}
您需要使您的服务可注射:
@Injectable()
export class GetWeatherService {
//CODE
}
在服务上添加@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);
}
}