IONIC FRAMEWORK TypeError: Object() не является функцией

Пожалуйста, помогите мне решить эту проблему, я застрял с этим почти 3 дня, это сводит меня с ума, я почти 10 раз проверяю, что в этом коде нет использования объекта в качестве функции. я использую google map api для ближайших местоположений, помогите мне решить это. Исходный код ниже, спасибо и извините за мой английский

TypeError: Object(...) не является функцией

Map.ts

   import { Component, NgZone } from '@angular/core';
    import { Geolocation } from '@ionic-native/geolocation';
    import { LoadingController } from 'ionic-angular';

    declare var google;

    @Component({
      selector: 'page-map',
      templateUrl: 'map.html'
    })
    export class MapPage {

      map: any;
      markers: any;
      autocomplete: any;
      GoogleAutocomplete: any;
      GooglePlaces: any;
      geocoder: any
      autocompleteItems: any;
      loading: any;

      constructor(
        public zone: NgZone,
        public geolocation: Geolocation,
        public loadingCtrl: LoadingController
      ) {
        this.geocoder = new google.maps.Geocoder;
        let elem = document.createElement("div")
        this.GooglePlaces = new google.maps.places.PlacesService(elem);
        this.GoogleAutocomplete = new google.maps.places.AutocompleteService();
        this.autocomplete = {
          input: ''
        };
        this.autocompleteItems = [];
        this.markers = [];
        this.loading = this.loadingCtrl.create();
      }

      ionViewDidEnter(){
          // let infoWindow = new google.maps.InfoWindow({map: map});
          //Set latitude and longitude of some place
        this.map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.9011, lng: -56.1645},
          zoom: 15
        });
      }

      tryGeolocation(){
        this.loading.present();
        this.clearMarkers();//remove previous markers

        this.geolocation.getCurrentPosition().then((resp) => {
          let pos = {
            lat: resp.coords.latitude,
            lng: resp.coords.longitude
          };
          let marker = new google.maps.Marker({
            position: pos,
            map: this.map,
            title: 'I am here!'
          });
          this.markers.push(marker);
          this.map.setCenter(pos);
          this.loading.dismiss();

        }).catch((error) => {
          console.log('Error getting location', error);
          this.loading.dismiss();
        });
      }

      updateSearchResults(){
        if (this.autocomplete.input == '') {
          this.autocompleteItems = [];
          return;
        }
        this.GoogleAutocomplete.getPlacePredictions({ input: this.autocomplete.input },
          (predictions, status) => {
            this.autocompleteItems = [];
            if(predictions){
              this.zone.run(() => {
                predictions.forEach((prediction) => {
                  this.autocompleteItems.push(prediction);
                });
              });
            }
        });
      }

      selectSearchResult(item){
        this.clearMarkers();
        this.autocompleteItems = [];

        this.geocoder.geocode({'placeId': item.place_id}, (results, status) => {
          if(status === 'OK' && results[0]){
            // let position = {
            //     lat: results[0].geometry.location.lat,
            //     lng: results[0].geometry.location.lng
            // };
            let marker = new google.maps.Marker({
              position: results[0].geometry.location,
              map: this.map
            });
            this.markers.push(marker);
            this.map.setCenter(results[0].geometry.location);
          }
        })
      }

      clearMarkers(){
        for (var i = 0; i < this.markers.length; i++) {
          console.log(this.markers[i])
          this.markers[i].setMap(null);
        }
        this.markers = [];
      }

    }

**Nearby.ts**

import { Component, NgZone } from '@angular/core';
import { LoadingController } from 'ionic-angular';


declare var google;
@Component({
  selector: 'nearby-map',
  templateUrl: 'nearby.html'
})
export class NearbyPage {


  autocomplete: any;
  GoogleAutocomplete: any;
  GooglePlaces: any;
  geocoder: any
  autocompleteItems: any;
  nearbyItems: any = new Array<any>();
  loading: any;

  constructor(
    public zone: NgZone,
    public loadingCtrl: LoadingController
  ) {

    this.geocoder = new google.maps.Geocoder;
    let elem = document.createElement("div")
    this.GooglePlaces = new google.maps.places.PlacesService(elem);
    this.GoogleAutocomplete = new google.maps.places.AutocompleteService();
    this.autocomplete = {
      input: ''
    };
    this.autocompleteItems = [];
    this.loading = this.loadingCtrl.create();
  }


  updateSearchResults(){
    if (this.autocomplete.input == '') {
      this.autocompleteItems = [];
      return;
    }
    this.GoogleAutocomplete.getPlacePredictions({ input: this.autocomplete.input },
      (predictions, status) => {
        this.autocompleteItems = [];
        if(predictions){
          this.zone.run(() => {
            predictions.forEach((prediction) => {
              this.autocompleteItems.push(prediction);
            });
          });
        }
    });
  }

  selectSearchResult(item){
    this.loading.present();
    this.autocompleteItems = [];
    this.geocoder.geocode({'placeId': item.place_id}, (results, status) => {
      if(status === 'OK' && results[0]){
        this.autocompleteItems = [];
        this.GooglePlaces.nearbySearch({
          location: results[0].geometry.location,
          radius: '500',
          types: ['restaurant'], //check other types here https://developers.google.com/places/web-service/supported_types
           key: 'AIzaSyCX8vBwodNkoemWblqcmPZHaWghGGRqLgw'
        }, (near_places) => {
          this.zone.run(() => {
            this.nearbyItems = [];
            for (var i = 0; i < near_places.length; i++) {
              this.nearbyItems.push(near_places[i]);
            }
            this.loading.dismiss();
          });
        })
      }
    })
  }
}

Index.js

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from '@angular/core';
import { Cordova, CordovaProperty, Plugin, IonicNativePlugin } from '@ionic-native/core';
/**
 * @name Status Bar
 * @description
 * Manage the appearance of the native status bar.
 *
 * Requires Cordova plugin: `cordova-plugin-statusbar`. For more info, please see the [StatusBar plugin docs](https://github.com/apache/cordova-plugin-statusbar).
 *
 * @usage
 * ```typescript
 * import { StatusBar } from '@ionic-native/status-bar';
 *
 * constructor(private statusBar: StatusBar) { }
 *
 * ...
 *
 * // let status bar overlay webview
 * this.statusBar.overlaysWebView(true);
 *
 * // set status bar to white
 * this.statusBar.backgroundColorByHexString('#ffffff');
 * ```
 *
 */
var StatusBar = (function (_super) {
    __extends(StatusBar, _super);
    function StatusBar() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Set whether the status bar overlays the main app view. The default
     * is true.
     *
     * @param {boolean} doesOverlay  Whether the status bar overlays the main app view.
     */
    StatusBar.prototype.overlaysWebView = function (doesOverlay) { };
    ;
    /**
     * Use the default statusbar (dark text, for light backgrounds).
     */
    StatusBar.prototype.styleDefault = function () { };
    ;
    /**
     * Use the lightContent statusbar (light text, for dark backgrounds).
     */
    StatusBar.prototype.styleLightContent = function () { };
    ;
    /**
     * Use the blackTranslucent statusbar (light text, for dark backgrounds).
     */
    StatusBar.prototype.styleBlackTranslucent = function () { };
    ;
    /**
     * Use the blackOpaque statusbar (light text, for dark backgrounds).
     */
    StatusBar.prototype.styleBlackOpaque = function () { };
    ;
    /**
     * Set the status bar to a specific named color. Valid options:
     * black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown.
     *
     * iOS note: you must call StatusBar.overlaysWebView(false) to enable color changing.
     *
     * @param {string} colorName  The name of the color (from above)
     */
    StatusBar.prototype.backgroundColorByName = function (colorName) { };
    ;
    /**
     * Set the status bar to a specific hex color (CSS shorthand supported!).
     *
     * iOS note: you must call StatusBar.overlaysWebView(false) to enable color changing.
     *
     * @param {string} hexString  The hex value of the color.
     */
    StatusBar.prototype.backgroundColorByHexString = function (hexString) { };
    ;
    /**
     * Hide the StatusBar
     */
    StatusBar.prototype.hide = function () { };
    ;
    /**
    * Show the StatusBar
    */
    StatusBar.prototype.show = function () { };
    ;
    StatusBar.decorators = [
        { type: Injectable },
    ];
    /** @nocollapse */
    StatusBar.ctorParameters = function () { return []; };
    __decorate([
        Cordova({    <!--- Showing error here --->
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Boolean]),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "overlaysWebView", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleDefault", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleLightContent", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleBlackTranslucent", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleBlackOpaque", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [String]),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "backgroundColorByName", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [String]),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "backgroundColorByHexString", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "hide", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "show", null);
    __decorate([
        CordovaProperty,
        __metadata("design:type", Boolean)
    ], StatusBar.prototype, "isVisible", void 0);
    StatusBar = __decorate([
        Plugin({
            pluginName: 'StatusBar',
            plugin: 'cordova-plugin-statusbar',
            pluginRef: 'StatusBar',
            repo: 'https://github.com/apache/cordova-plugin-statusbar',
            platforms: ['Android', 'iOS', 'Windows']
        })
    ], StatusBar);
    return StatusBar;
}(IonicNativePlugin));
export { StatusBar };
//# sourceMappingURL=index.js.map


//////////////////
// WEBPACK FOOTER
// ./node_modules/@ionic-native/status-bar/index.js
// module id = 283
// module chunks = 20

person Skull dev    schedule 18.08.2018    source источник
comment
Вы даже не дадите нам номер строки?   -  person Daedalus    schedule 19.08.2018
comment
как мне дать вам номер строки ?, я получил полный исходный код !!   -  person Skull dev    schedule 19.08.2018
comment
Добавьте полное сообщение об ошибке в свой ответ. Это будет включать номера строк, которые помогут нам диагностировать проблему.   -  person Chris    schedule 19.08.2018
comment
@Skulldev Сообщение об ошибке будет иметь номер строки. Полный исходный код не помогает нам сузить круг возможных проблем; вместо этого этот вопрос будет отложен как слишком широкий, учитывая, что вы ожидаете, что мы прочитаем весь код и выясним, в чем проблема. Это просто слишком много информации.   -  person Daedalus    schedule 19.08.2018
comment
Извините за это на index.js: 113   -  person Skull dev    schedule 19.08.2018
comment
@skull-dev, в этом случае вам также нужно будет показать нам полностью сгенерированный файл index.js.   -  person msbit    schedule 19.08.2018
comment
файл index.js показал   -  person Skull dev    schedule 20.08.2018


Ответы (1)


Как уже говорили другие, ваш вопрос очень широк, и вы не упомянули, какую версию ionic вы используете, но я попробую.

Предполагая, что вы используете Ionic 4, все ваши зависимости @ionic-native/* должны быть версии 5.0.0-beta.14.

Затем в вашем app.module.ts вы должны импортировать зависимость следующим образом: import { Geolocation } from '@ionic-native/geolocation/ngx'; Обратите внимание на /ngx в конце оператора.

Кроме того, вот проблема github с более подробной информацией: https://github.com/ionic-team/ionic/issues/15225

Очень похожий вопрос, который может помочь, здесь: Геолокация встроенного плагина Ionic 4 дает мне модуль не найден: Ошибка: не удается разрешить "rxjs/Observable"

person Mike    schedule 30.08.2018