简体   繁体   中英

Ionic can't find firebase

I've started a sample application using Ionic, and I started integrating Firebase Auth. For now, my application contains a single page show a login/password form. The integration seems to work properly, I can check if the user is authenticated and retrieve the user profile. However, my issue here is that after a little of testing, maybe after 10 minutes, or generally after another ionic serve , the following is returned :

Typescript Error
Cannot find name 'firebase'.
src/app/app.component.ts
firebase.auth().signInWithEmailAndPassword(this.form.value.email,  this.form.value.password).catch(function(error) {

Things might work again the next hour or so. Or after a complete reboot.

index.html :

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The main bundle js is generated during the build process -->
  <script src="build/main.js"></script>

  <script src="https://www.gstatic.com/firebasejs/4.5.1/firebase.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: "AIzaSyBiCVLhPuyfLV6qXI01IeTR_fcDs-dJoBY",
      authDomain: "racer-c6f75.firebaseapp.com",
      databaseURL: "https://racer-c6f75.firebaseio.com",
      projectId: "racer-c6f75",
      storageBucket: "racer-c6f75.appspot.com",
      messagingSenderId: "1070195339797"
    };
    firebase.initializeApp(config);
  </script>

</body>
</html>

app.component.ts :

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { FormBuilder, FormGroup } from '@angular/forms';

import { HomePage } from '../pages/home/home';
@Component({
  templateUrl: 'app.html'
})

export class MyApp {
  rootPage:any = HomePage;
  form : FormGroup;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      email: [''],
      password: ['']
    });

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }

  signInWithEmail(){
    console.log("XXXXX");
    console.dir(this.form.value);
    firebase.auth().signInWithEmailAndPassword(this.form.value.email,  this.form.value.password).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log(errorCode);
      console.log(errorMessage);

      // ...
    });
    console.log("YYY");
    var user = firebase.auth().currentUser;

    if (user) {
      // User is signed in.
      console.dir(user);
    } else {
      // No user is signed in.
    }
  }
}

app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Any idea ? I've tried wit AngularFire with similar results.

Typescript Error: Cannot find name 'firebase'.

Hotfix

Create globals.d.ts and add declare var firebase:any

Better fix

Don't include firebase in script and use the npm module that comes with typescript definitions. More : https://firebase.google.com/support/guides/firebase-web

npm install firebase
//first, download firebase with "npm install --save firebase"

// in app.components.ts
`Import firebase from 'firebase/app';`


// initialize your app with firebase details in app.modules.ts

`var app = firebase.initializeApp({
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>',
messagingSenderId: '<your-sender-id>'
});`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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