我在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();
}
我的Angular(前端)使用JSON主体发出POST请求,并将其发送到服务器,如下所示:
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);
});
}
我看到一条错误消息:
**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)**
seDeplacer()函数的调用方式如下:
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在初始化中被调用
init(): void{
this.getMap();
this.getHarry();
this.getMonsters();
this.combat = 0;
this.catchKeyEvent();
this.catchClickEvent();
}
问题出在this.http.post上。 通常我已经声明了私有的http:HttpClient;
您有什么建议吗?谢谢
答案 0 :(得分:1)
您应该利用依赖注入并像这样注入HttpClient:
import { HttpClient } from '@angular/common/http';
export class GameComponent implements OnInit {
constructor(private http: HttpClient)
...
}