Reputation: 1
I have the following pieces of code in Angular:
export class GameComponent implements OnInit {
@ViewChild('canvas', { static: true })
canvas: ElementRef<HTMLCanvasElement>;
private ctx: CanvasRenderingContext2D;
//public map: (BrickComponent|TileComponent|PlayerComponent)[][];
public harry: PlayerComponent;
private http: HttpClient;
private reponse : string;
private confirme : number;
private combat : number;
private maxX : number;
private maxY : number ;
private map: number[][];
private tab_monst : (MonsterComponent)[];
json;
ngOnInit(): void {
this.ctx = this.canvas.nativeElement.getContext('2d');
this.init();
}
My Angular (front-end) is making a POST request with JSON body and sends it to the server as follows :
seDeplacer(): void {
//const url = 'http://1:8080/api/Harry/update/';
const url = 'http://localhost:5200/api/Harry/update/';
console.log(this.harry);
// post body data
const response = {
"Id_Harry" : this.harry.getId,
"x_harry" : this.harry.getX(),
"y_harry" : this.harry.getY(),
"Pv_Harry" : this.harry.getPv(),
"Force_Harry" : this.harry.getForce()
};
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post(url, response, httpOptions).toPromise().then((data:any) => {
console.log(data);
console.log(data.json.test);
this.json = JSON.stringify(data.json);
});
}
I have an error that says :
**core.js:6014 ERROR TypeError: Cannot read property 'post' of undefined
at GameComponent.seDeplacer (game.component.ts:215)
at HTMLBodyElement.<anonymous> (game.component.ts:368)**
The seDeplacer() function is called like this:
catchKeyEvent(): void {
var elem = document.body;
elem.addEventListener("keyup", (event)=> {
var x = this.harry.getX(),
y = this.harry.getY();
if( 0 <= x && x < this.maxX && 0 <= y && y < this.maxY )
{
switch(event.keyCode)
{
//=>
case 39 :
this.seDeplacer();
this.harry.incX();
break;
//v
case 40 :
this.seDeplacer();
this.harry.incY();
break;
//<=
case 37 :
this.seDeplacer();
this.harry.decX();
break;
case 38 :
this.seDeplacer();
this.harry.decY();
break;
}
this.move(x,y);
}
});
catchKeyEvent is called in the init
init(): void{
this.getMap();
this.getHarry();
this.getMonsters();
this.combat = 0;
this.catchKeyEvent();
this.catchClickEvent();
}
the problem is with this.http.post. Normally I have declared the private http: HttpClient;
Do you have any suggestions? thank you
Upvotes: 0
Views: 226
Reputation: 119
You should make use of dependency injection and inject the HttpClient like this:
import { HttpClient } from '@angular/common/http';
export class GameComponent implements OnInit {
constructor(private http: HttpClient)
...
}
Upvotes: 1