首页 > 解决方案 > 使用异步等待获得角度位置的最佳方法是什么?

问题描述

这是我的代码,工作正常,但很难看。我的目标是在服务中做到这一点。但首先当我把异步等待功能不起作用:

看一下这个:

  ngOnInit() {
    this.getLocation();
  }

  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        this.position = position;
        this.makeSomething_1();
        this.makeSomething_3();
        this.makeSomething_4();
      }, positionError => {
        console.log('The user don accept location.');
        this.makeSomething_1();
        this.makeSomething_3();
        this.makeSomething_4();
      });
    } else {
      console.log('Geolocation is not supported by this browser.');
      this.makeSomething_1();
      this.makeSomething_3();
      this.makeSomething_4();
    }
  }

但我想做这样的事情:

 ngOnInit() {
    this.getLocation();
    this.makeSomething_1();
    this.makeSomething_3();
    this.makeSomething_4();
  }

async getLocation() {
    if (navigator.geolocation) {
      await navigator.geolocation.getCurrentPosition(position => {
        this.position = position;
      }, positionError => {
        console.log('The user don accept location.');
      });
    } else {
      console.log('Geolocation is not supported by this browser.');
    }
  }

我想要的问题是 this.position 打印“未定义”

有人可以教我如何编写好的代码吗?

请不要给我-1。我尽力了

标签: angularasync-await

解决方案


最快的方法是使用 RxJS 多播 observable 将结果缓存在服务中,例如ReplaySubject.

尝试以下

服务

import { ReplaySubject } from 'rxjs';

export class LocationService {
  private positionSource = new ReplaySubject(1);    // <-- buffer 1
  public position$ = this.positionSource.asObservable();

  constructor() {
    this.getLocation();
  }

  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        this.makeSomething_1();
        this.makeSomething_3();
        this.makeSomething_4();
        this.positionSource.next(position);
      }, positionError => {
        console.log('The user don accept location.');
        this.makeSomething_1();
        this.makeSomething_3();
        this.makeSomething_4();
      });
    } else {
      console.log('Geolocation is not supported by this browser.');
      this.makeSomething_1();
      this.makeSomething_3();
      this.makeSomething_4();
    }
  }
}

零件

export class SomeComponent implements OnInit {
  constructor(private _location: LocationService) { }

  ngOnInit() {
    this._location.position$.subscribe({
      next: position => {
        console.log('Got position: ', position);
        // do something else with `position`
      }
    });
  }
}

推荐阅读