gpt4 book ai didi

angular - 如何在 Angular 6 服务中发出 Http 请求

转载 作者:太空狗 更新时间:2023-10-29 18:28:50 30 4
gpt4 key购买 nike

这是我的事,我有一个消息服务,我想通过 HTTP 请求(Rest Api)从我的服务器收集数据,如下所示:

import { Sensor } from './sensor.model'
import { HttpClient } from '@angular/common/http';

export class MessageService{
mqttMessageData : JSON[]=[];
coapMessageData : JSON[]=[];
xmppMessageData : JSON[]=[];

constructor(private httpClient: HttpClient) {

}
getMqttMessages() {
this.httpClient.get<JSON>('http://127.0.0.1:5002/messages/mqtt').subscribe(data => {
this.mqttMessageData.push(data);
console.log(data);
});
}

但我的浏览器控制台出现此错误(ng serve 中没有错误):

Uncaught Error: Can't resolve all parameters for MessageService: (?).
at syntaxError (compiler.js:1016)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (compiler.js:10917)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (compiler.js:10810)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getInjectableTypeMetadata (compiler.js:11032)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getProviderMetadata (compiler.js:11041)
at compiler.js:10979
at Array.forEach (<anonymous>)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (compiler.js:10939)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:10416)
at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getEntryComponentMetadata (compiler.js:11013)

所以我假设 httpClient 有问题,但我不知道如何以其他方式做到这一点。

最佳答案

你需要在服务上添加@Injectable装饰器

import { Injectable } from '@angular/core'

@Injectable()
export class MessageService {
...
}

关于angular - 如何在 Angular 6 服务中发出 Http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51970430/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com