I am in using the HttpClient
module built into angular 7 to read a JSON from a server. When using the HttpClient
it always returns
ERROR TypeError: Cannot read property 'get' of undefined at push../src/app/info/info.component.ts.info.getVars (info.component.ts:37) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423) at Object.onInvokeTask (core.js:17290) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195) at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:498) at ZoneTask.invoke (zone.js:487) at timer (zone.js:2281)
I thought that this meant that the JSON couldn't be found/or was blank.
I have tried to read the JSON from the server (no success) and I have put the JSON into the assets folder to read it and I get the same error. I know that it should work in the assets folder because I can import it from the assets folder with no problem:import infoJson from '../../assets/info.json
This is what I have currently tried: (.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);
})
}
}
I have also tried creating a service, but I get the same error: (.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);
})
}
}
The reason why I want to use HttpClient
is because the JSON automatically updates with new data and I want to be able to read and display this.
Any help is appreciated.
EDIT
This is an example of the JSON I am trying to read:
{
"playerdata": [
{
"USER_ID": "7a8f",
"Status": 1,
"Start_Time": "2016-12-21 09:41:57",
"Finish_Time": "2016-12-21 09:43:17",
}
]
}
Also, this is my app.module.ts
:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
//components declared
],
imports: [
HttpClientModule,
//other imports here
],
providers: [ ],
bootstrap: [AppComponent]
})
export class AppModule { }
console.log(this.httpClient)
– jaredHttpClient(handler) { this.handler = handler; }
– JackU