类型 'Observable<any>' 不可分配给类型 'Observable<any>' Ionic 4

Type 'Observable<any>' is not assignable to type 'Observable<any>' Ionic 4

我目前正在使用 Google API 和 Ionic 4,我正在尝试实现一种在条目中获取地址和 returns 该地址的纬度和经度的方法(地理编码)。 在尝试实施该方法时,我遇到了这个问题:

类型 'Observable' 不可分配给类型 'Observable':

函数代码:

geocodeAddress(location: string): Observable<Location> {
  return this.waitForMapsToLoad().pipe(
  switchMap(() => {
    return new Observable(Location => {
      this.geocoder.geocode({address: location}, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {
          observer.next({
            lat: results[0].geometry.location.lat(),
            lng: results[0].geometry.location.lng()
          });
        } else {
          console.log('Error - ', results, ' & Status - ', status);
          observer.next({ lat: 0, lng: 0 });
        }
        observer.complete();
      });
    });
  })
);
}`

位置class:

export interface Location {
  lat: number;
  lng: number;
} 

进口:

import { Injectable } from '@angular/core';
import { MapsAPILoader } from '@agm/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { of } from 'rxjs/observable/of';
import { filter, catchError, tap, map, switchMap } from 'rxjs/operators';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Location } from './Position';

产生错误:

TS2322: Type 'Observable<unknown>' is not assignable to type 
'Observable<Location>'.   
Type '{}' is missing the following properties from 
type 'Location': lat, lng

我看到有人有这种问题,但不是同一个问题,你能帮帮我吗?

很可能您缺少某些值的某些类型,并且编译器无法确定您的 observable 的类型。

使用 new Observable<Location> 明确提及它,这应该会进一步指出另一个类型不匹配错误,或者使用

转换您的可观察对象
return new Observable(Location => {
  this.geocoder.geocode({address: location}, (results, status) => {
    if (status === google.maps.GeocoderStatus.OK) {
      observer.next({
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      });
    } else {
      console.log('Error - ', results, ' & Status - ', status);
      observer.next({ lat: 0, lng: 0 });
    }
    observer.complete();
  });
}) as Observable<Location>;

使用显式类型,您可以缩小到出现问题的行,并仅将您的转换应用到这一行。

编辑:通过 copy/pasting 你的代码,我注意到你使用 Location 作为你的 lambda 变量,我假设它是你在发布时犯的一个错误,并且它被正确设置为 observer 在你的代码中。