首页 > 解决方案 > 使用 Angular 7 检测位置

问题描述

我在使用 Angular 检测位置时遇到问题。

我知道为了检测位置,我使用 HTML5 地理定位 API。

window.navigator.geolocation.getCurrentPosition(
    (position) => {
      /* Location tracking code */
      this.currentLocation = position.coords;
      callback(position.coords);
    },
    (failure) => {
      if (failure.message.indexOf("Only secure origins are allowed") == 0) {
        alert('Only secure origins are allowed by your browser.');
      }
    }
  );

我的问题是当我在一个角度类中使用时,“this”总是指向成功函数而不是类本身。如何访问类属性?

请在下面找到完整的代码周期。

登陆页面

@Component({
  selector: 'app-landing-page',
  templateUrl: './landing-page.component.html',
  styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit {
  weatherDetailsArray: any = [];
  searchQuery: string = "";
  hasError: boolean = false;
  errorMessage: string = "";

  constructor(private _weatherService: WeatherService) { }

  ngOnInit() {
    // I get the location here and pass the function to be executed in the success callback
    this._weatherService._getLocation(this.detectLocation);
  }

  detectLocation (position) {
    const latLang = `${position.latitude}/${position.longitude}`;
    // "this" is undefined here
    this._weatherService.getCityWeatherDetails(latLang)
      .subscribe((res: any) => {
        let weatherDetails = this.mapWeatherResponse(res);
        this.weatherDetailsArray.push(weatherDetails);
      });
  }
}

WeatherService 中的代码

@Injectable({
  providedIn: 'root'
})
export class WeatherService {
  private _baseUrl = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key={some api key}&format=json";
  private currentLocation: any = {};

  constructor(private http: HttpClient) {}

  _getLocation(callback): void {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.getCurrentPosition(
        (position) => {
          // "this" here in the weather service is seen however currentLocation is always ""
          this.currentLocation = position.coords;
          callback(position.coords);
        },
        (failure) => {
          if (failure.message.indexOf("Only secure origins are allowed") == 0) {
            alert('Only secure origins are allowed by your browser.');
          }
        }
      );
    }
    else {
      console.log("Your browser doesn't support geolocation");
    }
  }

  getCityWeatherDetails(cityName: string = "Egypt") {
    return this.http.get(`${this._baseUrl}&num_of_days=5&includelocation=yes&tp=24&q=${cityName}`);
  }
}

我的问题在这里,我如何访问 this._weatherService.getCityWeatherDetails(latLang)

标签: angularangular7

解决方案


您的回调被作为函数而不是方法调用,因此它失去了this上下文:

this._weatherService._getLocation(this.detectLocation);

试试这个:

this._weatherService._getLocation(position => this.detectLocation(position));

或这个:

this._weatherService._getLocation(this.detectLocation.bind(this));

或切换到箭头功能:

detectLocation = (position) => { ... }

推荐阅读