集成 Firebase 到独立组件中

huangapple go评论68阅读模式
英文:

Integrating firebase into standalone component

问题

我有一个项目是用ionic angular制作的社交应用我想在其中包含firebase导入

provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore())

问题是这些导入应该在app.module.ts文件中而当前组件是一个独立的组件我不知道在哪里放置这些导入因为我应该导入

import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
import { getFirestore, provideFirestore } from '@angular/fire/firestore';
英文:

I have a project which is a social app made with ionic angular and I want to include the firebase imports in it

provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore())

The issue is that those imports should be in the app.module.ts file while the current component is a standalone component. I don't know where to put the imports as I should import:

import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
import { getFirestore, provideFirestore } from '@angular/fire/firestore';

答案1

得分: 4

你需要在应用程序启动时像这样提供你的Firebase应用程序:

bootstrapApplication(YourComponent, {
  providers: [
    importProvidersFrom(
      provideFirebaseApp(() => initializeApp(environment.firebase))
    ),
    importProvidersFrom(
      provideFirestore(() => getFirestore())
    )
  ]
});
英文:

Maybe you need to provide your firebase app on application bootstrapping like this:

bootstrapApplication(YourComponent, {
  providers: [
    importProvidersFrom(
      provideFirebaseApp(() => initializeApp(environment.firebase))
    ),
    importProvidersFrom(
      provideFirestore(() => getFirestore())
    )
  ]
});

答案2

得分: 1

这似乎是一个相当不错的解决方案。 免责声明:我是新手

main.ts

if (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    importProvidersFrom(IonicModule.forRoot()),
    provideRouter(routes),
    importProvidersFrom(provideFirebaseApp(() => initializeApp(environment.firebase)),
    importProvidersFrom(provideAnalytics(() => getAnalytics())),
    importProvidersFrom(provideAuth(() => getAuth())),
    importProvidersFrom(provideFirestore(() => getFirestore())),
    ScreenTrackingService,
    UserTrackingService,
  ],
});
英文:

This seems like a pretty good solution. disclaimer: I'm new to standalone

main.ts

if (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    importProvidersFrom(IonicModule.forRoot()),
    provideRouter(routes),
    importProvidersFrom(provideFirebaseApp(() => initializeApp(environment.firebase))),
    importProvidersFrom(provideAnalytics(() => getAnalytics())),
    importProvidersFrom(provideAuth(() => getAuth())),
    importProvidersFrom(provideFirestore(() => getFirestore())),
    ScreenTrackingService,
    UserTrackingService,
  ],
});

答案3

得分: 0

以下是代码的翻译部分:

我需要整理它但我正在使用

import { InjectionToken, NgModule } from '@angular/core';

import {
  FirebaseApp,
  initializeApp,
  provideFirebaseApp,
} from '@angular/fire/app';
import { provideAuth, getAuth, connectAuthEmulator } from '@angular/fire/auth';
import {
  provideFirestore,
  getFirestore,
  connectFirestoreEmulator,
  initializeFirestore,
} from '@angular/fire/firestore';

export interface IFirebaseConfig {
  apiKey: string;
  authDomain: string;
  projectId: string;
  locationId: string;
  storageBucket: string;
  messagingSenderId: string;
  appId: string;
  measurementId: string;
}

export const FIREBASE_CONFIG = new InjectionToken<IFirebaseConfig>(
  'FIREBASE_CONFIG',
  {
    providedIn: 'any',
    factory: () => {
      throw new Error(`提供 FIREBASE_CONFIG`);
    },
  }
);
export const USE_EMULATORS = new InjectionToken<boolean>('USE_EMULATORS', {
  providedIn: 'any',
  factory: () => {
    throw an Error(`提供 USE_EMULATORS`);
  },
});

@NgModule({
  declarations: [],
  imports: [
    provideFirebaseApp((injector) => {
      const config = injector.get(FIREBASE_CONFIG);
      console.log('🔮 提供FirebaseApp');
      return initializeApp(config);
    }),
    provideAuth((injector) => {
      console.log('🔮 提供Auth');
      const app = injector.get(FirebaseApp);
      const auth = getAuth(app);
      if (injector.get(USE_EMULATORS)) {
        console.log('🔮 使用Auth模拟器...');
        connectAuthEmulator(auth, 'http://localhost:9099');
      }
      return auth;
    }),
    provideFirestore((injector) => {
      console.log('🔮 提供Firestore');
      let firestore;
      if (injector.get(USE_EMULATORS)) {
        console.log(
          `🔮 使用Firestore模拟器...${
            injector.get(FIREBASE_CONFIG).projectId
          }`
        );
        // bug: experimentalAutoDetectLongPolling不通过`getFirestore`检测到
        const app = injector.get(FirebaseApp);
        firestore = initializeFirestore(app, {
          experimentalAutoDetectLongPolling: true,
        });
        connectFirestoreEmulator(firestore, 'localhost', 8080);
      } else {
        firestore = getFirestore();
      }
      return firestore;
    }),
  ],
})
export class FirebaseV7Module {}

然后,像在bootstrapApplication的提供者中添加以下内容,就像*provideFirebase()*一样:

importProvidersFrom(
 FirebaseV7Module
)

请注意,您还可以将提供者添加到路由器,以便不必将所有内容都放在根提供者中,但在这种情况下这样做是有道理的。

在新的独立世界中,不再是基于模块引导应用程序,而是基于main.ts中的组件引导应用程序:

import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
import { environment } from './environments/environment';

if (environment.production) {
    enableProdMode();
}

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));

appConfig与应用程序组件一起位于源文件中:

src/app/app.config.ts示例来自RealWorld Example App

export const appConfig: ApplicationConfig = {
  providers: [
    { provide: ApiConfiguration, useValue: { rootUrl: environment.apiUrl } },
    provideRouter(
      [
        {
          path: '',
          loadComponent: () => import('./layout/layout.component'),
          loadChildren: () => import('./layout/layout.routes'),
        },
      ],
      withHashLocation()
    ),
    provideHttpClient(withInterceptors([authInterceptor()])),
  ],
};

希望这可以帮助您。

英文:

I need to clean it up but I'm using:

import { InjectionToken, NgModule } from &#39;@angular/core&#39;;
import {
FirebaseApp,
initializeApp,
provideFirebaseApp,
} from &#39;@angular/fire/app&#39;;
import { provideAuth, getAuth, connectAuthEmulator } from &#39;@angular/fire/auth&#39;;
import {
provideFirestore,
getFirestore,
connectFirestoreEmulator,
initializeFirestore,
} from &#39;@angular/fire/firestore&#39;;
export interface IFirebaseConfig {
apiKey: string;
authDomain: string;
projectId: string;
locationId: string;
storageBucket: string;
messagingSenderId: string;
appId: string;
measurementId: string;
}
export const FIREBASE_CONFIG = new InjectionToken&lt;IFirebaseConfig&gt;(
&#39;FIREBASE_CONFIG&#39;,
{
providedIn: &#39;any&#39;,
factory: () =&gt; {
throw new Error(`Provide FIREBASE_CONFIG`);
},
}
);
export const USE_EMULATORS = new InjectionToken&lt;boolean&gt;(&#39;USE_EMULATORS&#39;, {
providedIn: &#39;any&#39;,
factory: () =&gt; {
throw new Error(`Provide USE_EMULATORS`);
},
});
@NgModule({
declarations: [],
imports: [
provideFirebaseApp((injector) =&gt; {
const config = injector.get(FIREBASE_CONFIG);
console.log(&#39;&#128276; provideFirebaseApp&#39;);
return initializeApp(config);
}),
provideAuth((injector) =&gt; {
console.log(&#39;&#128276; provideAuth&#39;);
const app = injector.get(FirebaseApp);
const auth = getAuth(app);
if (injector.get(USE_EMULATORS)) {
console.log(&#39;&#128276; using auth emulator...&#39;);
connectAuthEmulator(auth, &#39;http://localhost:9099&#39;);
}
return auth;
}),
provideFirestore((injector) =&gt; {
console.log(&#39;&#128276; provideFirestore&#39;);
let firestore;
if (injector.get(USE_EMULATORS)) {
console.log(
`&#128276; using firestore emulator...${
injector.get(FIREBASE_CONFIG).projectId
}`
);
// bug: experimentalAutoDetectLongPolling not picked up via `getFirestore`
const app = injector.get(FirebaseApp);
firestore = initializeFirestore(app, {
experimentalAutoDetectLongPolling: true,
});
connectFirestoreEmulator(firestore, &#39;localhost&#39;, 8080);
} else {
firestore = getFirestore();
}
return firestore;
}),
],
})
export class FirebaseV7Module {}

And then including the following like a provideFirebase() in the providers of bootstrapApplication:

importProvidersFrom(
FirebaseV7Module
)

Note you can also add providers to the router so not everything has to go onto the root provider but in this case it makes sense.

—-

In the new standalone world, instead of bootstrapping based off a module the application bootstraps based off a component in main.ts:

import { enableProdMode } from &#39;@angular/core&#39;;
import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;
import { AppComponent } from &#39;./app/app.component&#39;;
import { appConfig } from &#39;./app/app.config&#39;;
import { environment } from &#39;./environments/environment&#39;;
if (environment.production) {
enableProdMode();
}
bootstrapApplication(AppComponent, appConfig)
.catch((err) =&gt; console.error(err));

With appConfig collocated with the app component in source:

src/app/app.config.ts example from RealWorld Example App:

export const appConfig: ApplicationConfig = {
providers: [
{ provide: ApiConfiguration, useValue: { rootUrl: environment.apiUrl } },
provideRouter(
[
{
path: &#39;&#39;,
loadComponent: () =&gt; import(&#39;./layout/layout.component&#39;),
loadChildren: () =&gt; import(&#39;./layout/layout.routes&#39;),
},
],
withHashLocation()
),
provideHttpClient(withInterceptors([authInterceptor()])),
],
};

huangapple
  • 本文由 发表于 2023年3月31日 21:23:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定