简体   繁体   English

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

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

I am getting the following error:我收到以下错误:

Property 'subscribe' does not exist on type 'void'.ts(2339)类型“void”上不存在属性“订阅”.ts(2339)

when I try to use my AutoLocate function (below) by subscribing to it thusly:当我尝试通过订阅它来使用我的 AutoLocate function(下图)时:

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

Below is the AutoLocate function and also a GetAddress function that I use to get a complete model that uses Lat/Long and Address.下面是 AutoLocate function 和 GetAddress function,我用它来获取使用经/纬度和地址的完整 model。

  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;
    }));
  }
  

What am I doing wrong?我究竟做错了什么?

It appears you're mixing Promises with Observables.看来您正在将 Promises 与 Observables 混合在一起。 Moreover the AutoLocate() function isn't returning anything at the moment.此外,AutoLocate AutoLocate() function 目前不返回任何内容。

You could either convert observable to promise or vice-versa.您可以将 observable 转换为 promise,反之亦然。 I'd do the former using RxJS from function. Then you could apply the necessary operators to transform the data我会使用 function from RxJS 来做前者。然后你可以应用必要的运算符来转换数据

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
    })
  );
}

Breakdown:分解:

  1. from function to convert the promise to observable from function 将 promise 转换为可观察的
  2. NEVER constant to not emit to the subscription instead of a plain JS return; NEVER常量不发送到订阅而不是普通的 JS return;
  3. map operator to transform the emission to the required format map运算符将发射转换为所需格式
  4. switchMap operator to map from one observable to another switchMap运算符到 map 从一个可观察到另一个
  5. catchError operator to catch and trigger an alert. catchError运算符捕获并触发警报。 Note that catchError must return an observable.请注意, catchError必须返回一个可观察对象。 of function is used for that function. of用于 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM