Angular 跟踪游戏元素的位置
我想订阅一个元素的位置,以检查玩家是否丢失,我在我的app.module.ts中提供了一个窗口Angular 跟踪游戏元素的位置,angular,Angular,我想订阅一个元素的位置,以检查玩家是否丢失,我在我的app.module.ts中提供了一个窗口 providers: [ {provide: Window, useValue: window} ] 我添加了我的组件构造函数(私有窗口:window){} 当我添加到ngAfterViewInit() 我得到了正确的位置,但我想继续跟踪它,这样我就可以检查球员是否输了 这是组件 export class AppComponent implements AfterViewInit{
providers: [
{provide: Window, useValue: window}
]
我添加了我的组件构造函数(私有窗口:window){}
当我添加到ngAfterViewInit()
我得到了正确的位置,但我想继续跟踪它,这样我就可以检查球员是否输了
这是组件
export class AppComponent implements AfterViewInit{
title = 'first-game';
@ViewChild("personnage", {read: ElementRef}) myTrackedElement: ElementRef;
@ViewChild("ball", {read: ElementRef}) ball: ElementRef;
public isStarted = false;
public moveBall = false;
constructor(private window: Window){}
ngAfterViewInit() {
const topElement = parseInt(window.getComputedStyle(this.myTrackedElement.nativeElement).getPropertyValue("top"))
console.log(topElement)
}
}
谢谢你的帮助 ngAfterViewInit只执行一次。函数中可以有一个主题
//create a service auxiliar
@Injectable({
providedIn: 'root',
})
export class PlayerService {
constructor() { }
position$:Subject<number>=new Subject<number>();
sendPosition(element:ElementRef){
const topElement = parseInt(window.getComputedStyle(element.nativeElement)
.getPropertyValue("top"))
position$.next(topElement)
}
}
注1:我使用ngAfterInit订阅主题,您也可以在ngOnInit中订阅
注2:我创建了一个服务,但是如果你总是使用“玩家”,你可以在自己的组件中创建可观察的服务。很抱歉,我更新了我的帖子!谢谢你抽出时间!!
//create a service auxiliar
@Injectable({
providedIn: 'root',
})
export class PlayerService {
constructor() { }
position$:Subject<number>=new Subject<number>();
sendPosition(element:ElementRef){
const topElement = parseInt(window.getComputedStyle(element.nativeElement)
.getPropertyValue("top"))
position$.next(topElement)
}
}
export class AppComponent implements AfterViewInit{
constructor(private playerService:PlayerService){}
ngAfterViewInit(){
this.playerService.position$.subscribe(res=>{
console.log(res)
}
this.playerService.sendPosition(this.myTrackedElement);
}
//in another place
move(){
this.playerService.sendPosition(this.myTrackedElement);
}
}