You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Http服务中无法访问类变量该如何解决?

问题根因

  • this指向错误:你通过function关键字声明的successFunction属于独立函数,执行时this指向全局对象(严格模式下为undefined),而非当前GetApiService实例,因此无法访问类中定义的lati属性。
  • 异步逻辑顺序错误:navigator.geolocation.getCurrentPosition是异步API,回调函数successFunction会在apiCallForeCast方法执行return语句之后才会触发,哪怕解决了this指向问题,你返回请求时lati还未被赋值为定位获取的纬度值。

修复方案

  1. 用箭头函数定义成功回调,绑定正确的this指向
  2. 将定位回调逻辑包装为Observable,使用switchMap操作符在定位成功后再发起天气接口请求,保证请求参数是最新的定位值

修改后完整代码

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { from, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class GetApiService {
  lati = "123"

  constructor(private http: HttpClient) { }

  apiCallCurrent() {
    return this.http.get('https://api.met.no/weatherapi/nowcast/2.0/complete?lat=57.708870&lon=11.974560');
  }

  apiCallForeCast(): Observable<any> {
    if (!navigator.geolocation) {
      alert('当前浏览器不支持定位功能,请更换支持定位的浏览器后重试。');
      // 不支持定位的情况可返回错误Observable,或者用默认纬度发起请求
      return this.http.get(`https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=${this.lati}&lon=11.974560&altitude=12`);
    }

    // 将定位回调转为Observable
    const location$ = from(new Promise<GeolocationPosition>((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    }));

    // 定位成功后切换为天气请求
    return location$.pipe(
      switchMap(position => {
        const lat = position.coords.latitude;
        const long = position.coords.longitude;
        console.log('当前纬度:' + lat + ',当前经度:' + long);
        this.lati = lat.toString(); // 赋值给类属性
        console.log(this.lati);
        // 用获取到的纬度发起请求
        return this.http.get(`https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=${this.lati}&lon=11.974560&altitude=12`);
      })
    )
  }
}

内容的提问来源于stack exchange,提问作者erik johansson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:30:04