Angular 9 - 属性 'subscribe' 在类型 'void' 上不存在

Angular 9 - Property 'subscribe' does not exist on type 'void'

我收到以下错误:

Property 'subscribe' does not exist on type 'void'.ts(2339)

当我尝试通过订阅自动定位功能(如下)时:

this.AutoLocate().subscribe(data => { this.GotLoc = data});

下面是 AutoLocate 函数和 GetAddress 函数,我用它来获取使用 Lat/Long 和地址的完整模型。

  AutoLocate() {
    let AutoLocatedLocation: PlaceLocation;
    if(!Capacitor.isPluginAvailable('Geolocation')) {
      this.Alert.create({header: 'Location Service Error', message: 'Could not initialize Location Services! Please call support!'})
      return;
    }
    Plugins.Geolocation.getCurrentPosition().then(GeoPosition => {
      return this.coordinates = {lat: GeoPosition.coords.latitude, lng: GeoPosition.coords.longitude};
    }).then(coords => {
      this.GetAddress(coords.lat, coords.lng).subscribe(res => {
        this.Address = res;
        return AutoLocatedLocation = { lat: coords.lat, lng: coords.lng, address: res};
      });
    }).catch(error => {
      this.Alert.create({header: 'Location Service Error', message: 'Could not initialize Location Services! Please call support!'})
      console.log("Location: ", error);
    });
  }

  private GetAddress(lat: number, lng: number) {
    return this.http.get<any>(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${environment.googleMapsAPIKey}`)
    .pipe(map(geoData => {
      if (!geoData || !geoData.results || geoData.results.length === 0) {
        return null;
      }
      return geoData.results[0].formatted_address;
    }));
  }
  

我做错了什么?

您似乎将 Promises 与 Observables 混合在一起。此外,AutoLocate() 函数目前没有 returning 任何东西。

您可以将 observable 转换为 promise,反之亦然。我会使用 RxJS from 函数来做前者。然后你可以应用必要的运算符来转换数据

import { of, from, NEVER } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';

AutoLocate(): Observable<any> {     // <-- return type `Observable`
  let AutoLocatedLocation: PlaceLocation;
  if(!Capacitor.isPluginAvailable('Geolocation')) {
    this.Alert.create({header: 'Location Service Error', message: 'Could not initialize Location Services! Please call support!'})
    return NEVER;       // <-- use RxJS `NEVER` constant - it'll never emit
  }
  
  return from(Plugins.Geolocation.getCurrentPosition()).pipe(  // <-- return the observable
    switchMap(GeoPosition => {
      const coords = { lat: GeoPosition.coords.latitude, lng: GeoPosition.coords.longitude };
      this.coordinates = coords;  // <-- why is this needed though?
      return this.GetAddress(coords.lat, coords.lng).pipe(
        map(res => {
          this.Address = res;     // <-- again, is this needed here?
          return ({ ...coords, address: res });  // spread operator `...` retains old values while adding/modifying other values
        })
      )
    }),
    catchError(error => {
      this.Alert.create({header: 'Location Service Error', message: 'Could not initialize Location Services! Please call support!'});
      return of(error);           // <-- `catchError` must return an observable
    })
  );
}

细分:

  1. from 将 promise 转换为 observable 的函数
  2. NEVER 不发送到订阅而不是普通 JS 的常量 return;
  3. map 运算符将发射转换为所需格式
  4. switchMap 运算符将一个可观察对象映射到另一个
  5. catchError 运算符捕获并触发警报。请注意 catchError 必须 return 是可观察的。 of 函数用于该函数。