我正在尝试使用Angular 5中的服务。这就是我所拥有的:
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
constructor() { }
getData() {
// don't use 'any', type your data instead!
return this.httpClient.get<any>('./assets/data.json');
}
}
我收到以下错误:
属性HttpClient在DataService类型上不存在。
我错过了什么?
答案 0 :(得分:3)
您需要从模块中导入HttpClient,如下所示
import {HttpClient} from '@angular/common/http';
你的代码应该是这样的
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private httpClient: HttpClient) { }
getData() {
// don't use 'any', type your data instead!
return this.httpClient.get<any>('./assets/data.json');
}
}
答案 1 :(得分:2)
试试这样:
阅读更多关于httpClient here
的信息import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private httpClient: HttpClient) { }
getData() {
// don't use 'any', type your data instead!
return this.httpClient.get<any>('./assets/data.json');
}
}
答案 2 :(得分:0)
考虑按如下方式更新代码:
import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
@Injectable()
export class DataService {
constructor(private httpClient: Http) { }
getData() {
// don't use 'any', type your data instead!
return this.httpClient.get<any>('./assets/data.json');
}
}
让我知道它是否有效。
答案 3 :(得分:0)
Http Calls已被修改并移至&#39; @ angular / common / http&#39;作为HttpClient,因为这个想法得到了许多开发人员的支持,因为它转移到了@ angular / common / http&#39;来自Angular 4.3,并从Angular 5中弃用了@ angular / http的进一步Http模块。请查看此处的更改:https://jaxenter.com/road-to-angular-5-133253.html。
现在问题,您应该导入HttpClient模块并创建它的实例。 所以你的代码就像: -
从@ angular / core&#39;导入{Injectable}; 从&#39; @ angular / common / http&#39;;
导入{HttpClient}@Injectable() 导出类DataService {
constructor(private _httpClient: HttpClient) { }
getData() {
// don't use 'any', type your data instead!
return this._httpClient.get<any>('./assets/data.json');
}
}
答案 4 :(得分:0)
对我来说,问题是我的构造函数中没有将 httpClient 列为 private。
原始构造函数:
constructor(
httpClient: HttpClient
) { }
更新了解决错误的构造函数:
constructor(
private httpClient: HttpClient
) { }