我正在使用角度7中内置的HttpClient
模块从服务器读取JSON。使用HttpClient
时,它始终返回
错误TypeError:无法读取未定义的属性“ get” 在推送../src/app/info/info.component.ts.info.getVars(info.component.ts:37) 在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask(zone.js:423) 在Object.onInvokeTask(core.js:17290) 在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask(zone.js:422) 在Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask(zone.js:195) 在push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask(zone.js:498) 在ZoneTask.invoke(zone.js:487) 在计时器(zone.js:2281)
我认为这意味着无法找到JSON /或为空白。
我尝试从服务器读取JSON(没有成功),并且将JSON放入assets文件夹中以读取它,但遇到相同的错误。我知道它应该在Assets文件夹中工作,因为我可以毫无问题地从Assets文件夹导入它:
import infoJson from '../../assets/info.json
这是我目前正在尝试的:( .component.ts )
import { HttpClient } from '@angular/common/http'
export class VehicleinfoComponent implements OnInit {
constructor(private httpService: HttpClient ) { }
getVars() {
this.httpService.get('../../assets/info.json').subscribe(data => {
console.log(data);
})
}
}
我也曾尝试创建服务,但出现相同的错误:( .service.ts ):
import { HttpClient } from '@angular/common/http';
import { Observable} from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class GetJsonService {
constructor(private http: HttpClient) { }
public getJsonInfo(): Observable<any> {
return this.http.get('./assets/info.json')
}
}
.component.ts :
import { GetJsonService } from '../get-json.service'
export class VehicleinfoComponent implements OnInit {
constructor(private GetJson: GetJsonService) { }
getVars() {
this.GetJson.getJsonInfo().subscribe(data => {
console.log(data);
})
}
}
我要使用HttpClient
的原因是因为JSON自动使用新数据更新,并且我希望能够读取和显示它。
感谢您的帮助。
编辑
这是我尝试读取的JSON的示例:
{
"playerdata": [
{
"USER_ID": "7a8f",
"Status": 1,
"Start_Time": "2016-12-21 09:41:57",
"Finish_Time": "2016-12-21 09:43:17",
}
]
}
另外,这是我的app.module.ts
:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
//components declared
],
imports: [
HttpClientModule,
//other imports here
],
providers: [ ],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:-2)
this.httpService
这里的httpService
是undefined
意味着没有发生注入。
请仔细检查模块配置,如果您声明了正确的提供程序(并且它是自定义的,则可以使用)。
属性导入应如下所示:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule, // HERE
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}