Using GeoFire in an Angular2 App

前端 未结 2 2060
刺人心
刺人心 2021-01-03 13:36

I\'m trying to set up GeoFire in my Angular2 (RC5) app. I\'ve installed geofire and firebase with npm and configured systemjs to import it. Here\'s my package.json:

相关标签:
2条回答
  • 2021-01-03 14:26

    Notice, I'm still not a TypeScript expert and this is my first time dabbling with type definitions and such, but after a long work day I seem to have got something that works (at least for my setup). I'm using Ionic 2 RC2, Angular2 2.1.1, Geofire 4.1.2. The build uses webpack. I created geofire.d.ts in my app directory with the following:

    declare module 'geofire' {
    
        type EventType = 'ready' | 'key_entered' | 'key_exited' | 'key_moved';
    
        interface GeoQueryCriteria {
            center: number[];
            radius: number;
        }
    
        interface GeoQueryUpdateCriteria {
            center?: number[];
            radius?: number;
        }
    
        interface GeoCallbackRegistration {
            cancel();
        }
    
        interface GeoQuery {
            center(): number[];
            radius(): number;
            updateCriteria(criteria: GeoQueryUpdateCriteria);
            on(eventType: EventType, callback: (key:string, location: number[], distance: number) => void): GeoCallbackRegistration;
            cancel();
        }
    
        class GeoFire {
            constructor(ref: any);
            ref(): any;
            set(key: string, loc: number[]): Promise<void>;
            get(key: string): Promise<number[]>;
            remove(key: string): Promise<void>;
            query(criteria: GeoQueryCriteria): GeoQuery;
            static distance(location1: number[], location2: number[]);  
        }
    
        export = GeoFire;
    }
    

    Finally in my Service/Page I can import GeoFire like so:

    import GeoFire from 'geofire';

    Note the exact syntax of the import there are no curly braces {}. I tried so many ways to get it to work differently but I think the way the javascript was written, this is how it has to be done. I found ways that would get rid of compile errors, but fail at runtime ('no constructor named...'), or it would recognize the constructor in compilation but not as a type.

    I only created it for the public API so if you try to extend GeoFire for some reason be aware there could be name conflicts with other methods not exposed in this definition file.

    If this helps you out please let me know and I'll contribute it to DefinitelyTyped so no one else has to go through the pain I (and obviously others with 340+ views) did.

    0 讨论(0)
  • 2021-01-03 14:37

    That quickstart tutorial is missing one important point: SystemJS and TypeScript are two separate tools, each with its own configuration.

    Adding geofire to systemjs config has no effect on typescript module resolution. Upon seeing this import

    import * as GeoFire from "geofire";
    

    tsc tries to find geofire.ts in usual places where typings for javascript modules are normally found, and gives an error because it's not there.

    There are three different ways to solve this problem.

    In any case, geofire package configuration in systemjs.config.js must declare its format as global, like this:

    'geofire': {
        main: 'dist/geofire.js', 
        defaultExtension: 'js', 
        meta: {'dist/geofire.js': {format: 'global'}} 
     },
    

    The first solution is to create the simplest possible type declaration for geofire yourself, using ambient modules.

    Create geofire.d.ts file in the app folder:

    declare namespace geofire {
        function GeoFire(firebaseRef: any): void;
    }
    
    declare module 'geofire' {
        export = geofire;
    }
    

    This is sufficient for import statement to compile, and for this call to typecheck:

       var geoFire = new GeoFire(firebaseRef);
    

    NOTE for typescript 2.0

    For typescript 2.0 the code above does not work. You have to use typescript-specific import = syntax

    import GeoFire = require('geofire');
    

    and change definition in geofire.d.ts to:

    declare module 'geofire' {
        function GeoFire(firebaseRef: any): void;
        export = GeoFire;
    }
    

    Yet another possible way to solve this is to use a plugin for SystemJS that uses TypeScript API to invoke typescript and hook into its module resolution, so that it takes into account SystemJS configuration. With that plugin, that import will work at runtime in the browser, but invoking tsc from the command line would still give the same error.

    The third way is to import geofire using SystemJS API, not the import statement in app.component.ts:

    import { Component } from '@angular/core';
    
    declare var SystemJS : any;
    var GeoFirePromise = SystemJS.import('geofire');
    
    @Component({
      selector: 'my-app',
      template: '<h1>My First Angular 2 App</h1>'
    })
    
    export class AppComponent {
    
        constructor() {  // or wherever you need to use geofire
    
            GeoFirePromise.then(function(GeoFire: any) {
                console.log(typeof GeoFire);
            });
        }
    
    }
    

    Note that SystemJS.import returns a promise that will have to load geofire.js, so anywhere you want to use it you have to do

        GeoFirePromise.then(function(GeoFire: any) {
    

    If this is inconvenient, you can just declare global GeoFire variable

    declare var GeoFire: any;
    

    and load geofire.js using script tag in your HTML, as described in this post on ionic forum. Then, you would not event need to add geofire to systemjs.config.js.

    0 讨论(0)
提交回复
热议问题