### Create New Angular Project with CLI Source: https://github.com/angular/angularfire/blob/main/site/src/get-started/quick-start.md Installs the Angular CLI globally and creates a new Angular project with the specified name. Navigates into the newly created project directory. ```bash npm install -g @angular/cli ng new cd ``` -------------------------------- ### Install Ionic CLI and Update Source: https://github.com/angular/angularfire/blob/main/site/src/ionic/getting-started.md Installs or updates the Ionic CLI to the latest version, ensuring compatibility with the project. Requires npm and Node.js. ```bash npm uninstall -g ionic npm cache clean # reinstall clean version npm install -g @ionic/cli ``` -------------------------------- ### Install ExpressJS and Dependencies Source: https://github.com/angular/angularfire/blob/main/site/src/universal/getting-started.md Installs necessary development dependencies for building an ExpressJS server with Angular Universal. Includes packages for the Express engine, module map loader, Webpack, and polyfills. ```bash npm install --save-dev @nguniversal/express-engine @nguniversal/module-map-ngfactory-loader express webpack-cli ts-loader ws xhr2 ``` -------------------------------- ### Install AngularFire and Firebase Packages Source: https://github.com/angular/angularfire/blob/main/site/src/ionic/getting-started.md Installs the necessary AngularFire and Firebase npm packages for integration into an Angular project. Requires npm. ```bash npm install @angular/fire firebase --save ``` -------------------------------- ### Package.json Build Scripts for SSR Source: https://github.com/angular/angularfire/blob/main/site/src/universal/getting-started.md Example 'scripts' section in `package.json` for building and serving the Angular Universal application. Includes commands for a full build, SSR build, Webpack bundling, and serving the SSR output. ```json "scripts": { // ... omitted "build": "ng build && npm run build:ssr", "build:ssr": "ng run YOUR_PROJECT_NAME:server && npm run webpack:ssr", "webpack:ssr": "webpack --config webpack.server.config.js", "serve:ssr": "node dist/YOUR_PROJECT_NAME-webpack/server.js" }, ``` -------------------------------- ### Initialize Firebase Project (CLI, npx, yarn) Source: https://github.com/angular/angularfire/blob/main/docs/install-firebase-tools.md Initializes Firebase tools for your project. This command prompts you to log in and configure Firebase features. It can be run directly if installed globally, or via `npx` or `yarn` if installed locally as a dependency. Requires an active internet connection and a Firebase account. ```bash firebase init ``` ```bash npx firebase init ``` ```bash yarn firebase init ``` -------------------------------- ### Serve Ionic Application Source: https://github.com/angular/angularfire/blob/main/site/src/ionic/getting-started.md Starts a local development server to preview the Ionic application in a browser. Useful for testing during development. Requires Ionic CLI. ```bash ionic serve ``` -------------------------------- ### Angular Module Setup for Firebase Analytics Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md This snippet shows the basic setup for integrating AngularFire Analytics into your Angular application's root module. It imports necessary modules and initializes Firebase. ```typescript import { AngularFireModule } from '@angular/fire'; import { AngularFireAnalyticsModule } from '@angular/fire/analytics'; import { environment } from '../environments/environment'; import { NgModule } from '@angular/core'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ] }) export class AppModule { } ``` -------------------------------- ### Install Firebase Tools Globally (npm, yarn) Source: https://github.com/angular/angularfire/blob/main/docs/install-firebase-tools.md Installs the Firebase CLI globally on your system using either npm or yarn. This makes the `firebase` command available in any directory. No specific inputs or outputs, but requires Node.js and npm/yarn to be installed. ```bash npm install -g firebase-tools ``` ```bash yarn global add firebase-tools ``` -------------------------------- ### Select Firebase Features for Initialization Source: https://github.com/angular/angularfire/blob/main/docs/install-firebase-tools.md This interactive CLI prompt allows you to select which Firebase services (e.g., Firestore, Hosting, Functions) you want to set up for your current project directory. Use spacebar to select/deselect, `a` to toggle all, `i` to invert selection, and Enter to confirm. No code output, but configures project settings. ```bash ? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to confirm your choices. (Press to select (option) to toggle all, to invert selection, and to proceed) ◯ Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default instance ◯ Firestore: Configure security rules and indexes files for Firestore ◯ Functions: Configure a Cloud Functions directory and its files ◯ Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys ◯ Hosting: Set up GitHub Action deploys (Move up and down to reveal more choices) ``` -------------------------------- ### Install Angular CLI and Create Project Source: https://github.com/angular/angularfire/blob/main/docs/install-and-setup.md This option involves globally installing the Angular CLI and then using it to create a new Angular project. The `ng new` command sets up the latest Angular build and project structure. ```bash # Installing the tooling directly npm install -g @angular/cli ng new cd ``` -------------------------------- ### Angular Module Setup for Performance Monitoring Source: https://github.com/angular/angularfire/blob/main/site/src/performance/getting-started.md This snippet demonstrates how to import and configure `AngularFirePerformanceModule` in your Angular application's AppModule to enable automatic page load tracing. It requires Firebase environment configuration and the `PerformanceMonitoringService` to be provided. ```typescript import { AngularFireModule } from '@angular/fire'; import { AngularFirePerformanceModule, PerformanceMonitoringService } from '@angular/fire/performance'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebase), AngularFirePerformanceModule, ... ], providers: [ PerformanceMonitoringService ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {} ``` -------------------------------- ### Angular Module Setup for Analytics Source: https://github.com/angular/angularfire/blob/main/docs/compat/analytics/getting-started.md Configures the Angular application to use AngularFire Analytics by importing the necessary modules. This setup automatically handles the initialization of analytics. ```typescript import { AngularFireAnalyticsModule } from '@angular/fire/compat/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ] }) export class AppModule { } ``` -------------------------------- ### AngularFire Performance Monitoring Setup Source: https://github.com/angular/angularfire/blob/main/docs/compat/performance/getting-started.md Set up automatic page load tracing by importing `AngularFirePerformanceModule` into your AppModule. This automatically instruments page load performance metrics. Ensure Firebase is initialized with `AngularFireModule.initializeApp`. ```typescript import { AngularFireModule } from '@angular/fire/compat'; import { AngularFirePerformanceModule, PerformanceMonitoringService } from '@angular/fire/compat/performance'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebase), AngularFirePerformanceModule, ... ], providers: [ PerformanceMonitoringService ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {} ``` -------------------------------- ### AngularFireAuth: Monitor User State and Handle Auth Source: https://github.com/angular/angularfire/blob/main/site/src/auth/getting-started.md This snippet demonstrates how to use AngularFireAuth to observe the user's authentication state via an Observable. It includes examples for logging in with Google and logging out. This requires the AngularFireAuth module and Firebase setup. ```typescript import { Component } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import firebase from 'firebase/app'; @Component({ selector: 'app-root', template: `{%raw%}

Hello {{ user.displayName }}!

Please login.

{%endraw%}`, }) export class AppComponent { constructor(public auth: AngularFireAuth) { } login() { this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()); } logout() { this.auth.signOut(); } } ``` -------------------------------- ### Configuration with Dependency Injection Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Allows configuration of Google Analytics using the `CONFIG` DI Token. ```APIDOC ## Configuration with Dependency Injection ### Using the CONFIG DI Token The `CONFIG` DI Token (*default: {}*) allows you to configure Google Analytics. For example, to skip the initial `page_view` event, anonymize IP addresses, and disallow ads personalization signals: ```typescript import { AngularFireAnalyticsModule, CONFIG } from '@angular/fire/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ { provide: CONFIG, useValue: { send_page_view: false, allow_ad_personalization_signals: false, anonymize_ip: true } } ] }) export class AppModule { } ``` Refer to the gtag.js documentation for available configuration options. ``` -------------------------------- ### Connect Repo to Firebase Project Option Selection Source: https://github.com/angular/angularfire/blob/main/docs/install-firebase-tools.md Presents options to link your project's repository to a Firebase project during the `firebase init` process. You can choose to use an existing project, create a new one, add Firebase to an existing Google Cloud Platform project, or skip project setup. This step configures the project's deployment target. ```bash ? Please select an option: ◯ Use an existing project ◯ Create a new project ◯ Add Firebase to an existing Google Cloud Platform project ◯ Don't set up a default project ``` -------------------------------- ### Track Deployments Configuration Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Enables tracking deployment versions by providing `APP_NAME` and `APP_VERSION`. ```APIDOC ## Track Deployments If you provide `APP_NAME` and `APP_VERSION` (*default: undefined*), you will be able to [track version adoption](https://console.firebase.google.com/project/_/analytics/latestrelease) of your PWA. ``` -------------------------------- ### Configuring Google Analytics with DI Token CONFIG Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md This example demonstrates how to customize Google Analytics behavior using the `CONFIG` DI token. It disables the automatic 'page_view' event, anonymizes IP addresses, and disallows ad personalization. ```typescript import { AngularFireAnalyticsModule, CONFIG } from '@angular/fire/analytics'; import { AngularFireModule } from '@angular/fire'; import { environment } from '../environments/environment'; import { NgModule } from '@angular/core'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ { provide: CONFIG, useValue: { send_page_view: false, allow_ad_personalization_signals: false, anonymize_ip: true } } ] }) export class AppModule { } ``` -------------------------------- ### AngularFireAnalytics Usage Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Demonstrates how to import and use AngularFireAnalytics in your Angular application. ```APIDOC ## Usage ### Importing the Module ```typescript import { AngularFireAnalyticsModule } from '@angular/fire/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ] }) export class AppModule { } ``` ### Injecting and Using AngularFireAnalytics ```typescript import { AngularFireAnalytics } from '@angular/fire/analytics'; constructor(analytics: AngularFireAnalytics) { analytics.logEvent('custom_event', { ... }); } ``` ``` -------------------------------- ### RxJS Operator for Performance Tracing in AngularFire Source: https://github.com/angular/angularfire/blob/main/site/src/performance/getting-started.md This example illustrates using the `trace` RxJS operator provided by AngularFire to measure the time between Observable subscription and its first emission or completion. This operator integrates with performance monitoring tools. ```typescript import { trace } from '@angular/fire/performance'; // ... constructor(private performance: AngularFirePerformance, private afs: AngularFirestore) {} ngOnInit() { this.articles = afs.collection('articles') .collection('articles', ref => ref.orderBy('publishedAt', 'desc')) .snapshotChanges() .pipe( // measure the amount of time between the Observable being subscribed to and first emission (or completion) trace('getArticles'), map(articles => ...) ); } ``` -------------------------------- ### Create a New Ionic Project Source: https://github.com/angular/angularfire/blob/main/site/src/ionic/getting-started.md Scaffolds a new Ionic project using the Ionic CLI. Prompts the user to select a template and sets up the project structure. Requires Ionic CLI. ```bash ionic start cd ``` -------------------------------- ### AngularFireAnalytics API Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Provides methods for interacting with Firebase Analytics, including logging events, setting user properties, and managing collection. ```APIDOC ## Class: AngularFireAnalytics ### Description Provides a promisified interface to the Firebase Analytics SDK. ### Methods * **updateConfig(options: {[key:string]: any}): Promise** Updates the analytics configuration. * **logEvent(eventName: string, eventParams?: {[key: string]: any}, options?: analytics.AnalyticsCallOptions): Promise** Logs a custom analytics event. - **eventName** (string) - Required - The name of the event to log. - **eventParams** ({[key: string]: any}) - Optional - Parameters for the event. - **options** (analytics.AnalyticsCallOptions) - Optional - Call options. * **setCurrentScreen(screenName: string, options?: analytics.AnalyticsCallOptions): Promise** Sets the current screen name in analytics. - **screenName** (string) - Required - The name of the screen. - **options** (analytics.AnalyticsCallOptions) - Optional - Call options. * **setUserId(id: string, options?: analytics.AnalyticsCallOptions): Promise** Sets the user ID for analytics. - **id** (string) - Required - The user ID. - **options** (analytics.AnalyticsCallOptions) - Optional - Call options. * **setUserProperties(properties: analytics.CustomParams, options?: analytics.AnalyticsCallOptions): Promise** Sets user properties for analytics. - **properties** (analytics.CustomParams) - Required - The user properties to set. - **options** (analytics.AnalyticsCallOptions) - Optional - Call options. * **setAnalyticsCollectionEnabled(enabled: boolean): Promise** Enables or disables analytics collection. - **enabled** (boolean) - Required - Whether to enable collection. * **app: Promise** A promise that resolves with the Firebase App instance. ### Tokens * **COLLECTION_ENABLED** (InjectionToken) * **APP_VERSION** (InjectionToken) * **APP_NAME** (InjectionToken) * **DEBUG_MODE** (InjectionToken) * **CONFIG** (InjectionToken) ``` -------------------------------- ### Filtering and Fetching Specific Remote Config Parameters Source: https://github.com/angular/angularfire/blob/main/site/src/remote-config/getting-started.md This example demonstrates how to specifically observe and fetch a single Remote Config parameter, `titleBackgroundColor`, as a string. It uses RxJS operators like `filter`, `map`, `budget`, and `last` to control the emission of values, ensuring the freshest possible value within a specified time budget without aborting server fetches. ```typescript remoteConfig.changes.pipe( filter(param => param.key === 'titleBackgroundColor'), map(param => param.asString()) // budget at most 800ms and return the freshest value possible in that time // our budget pipe is similar to timeout but won't error or abort the pending server fetch // (it won't emit it, if the deadline is exceeded, but it will have been fetched so can use the // freshest values on next subscription) budget(800), last() ).subscribe(...) ``` -------------------------------- ### Screen Tracking Service Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Automatically logs `screen_view` events by integrating with the Angular Router. ```APIDOC ## Tracking Screen Views ### Integrating ScreenTrackingService ```typescript import { AngularFireAnalyticsModule, ScreenTrackingService } from '@angular/fire/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ ScreenTrackingService ] }) export class AppModule { } ``` `AngularFireAnalyticsModule` will initialize `ScreenTrackingService` if it is provided. This service automatically integrates with the Angular Router to provide Firebase with screen view tracking. ``` -------------------------------- ### Download File Metadata using AngularFireStorage Source: https://github.com/angular/angularfire/blob/main/site/src/storage/getting-started.md Fetches and displays metadata associated with a file stored in Cloud Storage using AngularFireStorage. This allows access to file information without downloading the file itself. ```typescript @Component({ selector: 'app-root', template: `{%raw%}
{{ meta | async }}
{%endraw%}` }) export class AppComponent { meta: Observable; constructor(private storage: AngularFireStorage) { const ref = this.storage.ref('users/davideast.jpg'); this.meta = ref.getMetadata(); } } ``` -------------------------------- ### AngularFireAuth: Configure Auth Settings with SETTINGS DI Token Source: https://github.com/angular/angularfire/blob/main/docs/compat/auth/getting-started.md Shows how to configure Firebase Auth instance settings using the SETTINGS DI Token in an Angular application's AppModule. This example specifically enables app verification disabling for testing phone authentication. ```typescript import { SETTINGS as AUTH_SETTINGS } from '@angular/fire/compat/auth'; import { NgModule } from '@angular/core'; @NgModule({ // ... Existing configuration providers: [ // ... Existing Providers { provide: AUTH_SETTINGS, useValue: { appVerificationDisabledForTesting: true } }, ] }) export class AppModule { } ``` -------------------------------- ### Manual Trace Measurement with AngularFirePerformance Source: https://github.com/angular/angularfire/blob/main/site/src/performance/getting-started.md This code snippet shows how to inject `AngularFirePerformance` into an Angular component and use it to manually start and stop a trace. This allows you to measure the duration of specific operations within your application. ```typescript constructor(private performance: AngularFirePerformance) {} // ... const trace = await this.performance.trace('some-trace'); trace.start(); // Dome something you want to trace trace.stop(); ``` -------------------------------- ### DebugView Configuration Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Enables DebugView in Analytics by setting the `DEBUG_MODE` token to true. ```APIDOC ## Use DebugView To use [DebugView in Analytics](https://console.firebase.google.com/project/_/analytics/debugview), set `DEBUG_MODE` to `true` (*default: false*). ``` -------------------------------- ### Initial Setup for AngularFire Development Source: https://github.com/angular/angularfire/blob/main/CONTRIBUTING.md This section details the steps required to set up your local development environment for AngularFire. It involves forking the repository, cloning it, installing dependencies, building the project, and running tests. ```shell git clone cd angularfire npm i npm run build npm run test:all ``` ```shell git checkout -b my-fix-branch master ``` -------------------------------- ### Import AngularFireStorageModule in NgModule Source: https://github.com/angular/angularfire/blob/main/site/src/storage/getting-started.md Import `AngularFireStorageModule` to enable Cloud Storage functionalities within your Angular application. This sets up the `AngularFireStorage` service for dependency injection. Ensure `AngularFireModule.initializeApp` is also included. ```typescript import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { AngularFireModule } from '@angular/fire'; import { AngularFireStorageModule } from '@angular/fire/storage'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebase), AngularFireStorageModule ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} ``` -------------------------------- ### Injecting AngularFireStorage Service in Component Source: https://github.com/angular/angularfire/blob/main/site/src/storage/getting-started.md Inject the `AngularFireStorage` service into your Angular components to interact with Cloud Storage. This service provides methods for uploading and managing files. ```typescript import { Component } from '@angular/core'; import { AngularFireStorage } from '@angular/fire/storage'; @Component({ selector: 'app-component', template: `` }) export class AppComponent { constructor(private storage: AngularFireStorage) { } } ``` -------------------------------- ### Enabling Automatic Screen View Tracking with ScreenTrackingService Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md This configuration enables automatic tracking of screen views by integrating the `ScreenTrackingService` with the Angular Router. It requires providing the service in the module. ```typescript import { AngularFireAnalyticsModule, ScreenTrackingService } from '@angular/fire/analytics'; import { AngularFireModule } from '@angular/fire'; import { environment } from '../environments/environment'; import { NgModule } from '@angular/core'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ ScreenTrackingService ] }) export class AppModule { } ``` -------------------------------- ### Generate Angular Universal Server Module Source: https://github.com/angular/angularfire/blob/main/site/src/universal/getting-started.md Command to generate the Angular Universal server module using the Angular CLI. This is a prerequisite for setting up server-side rendering. ```bash ng generate universal --client-project ``` -------------------------------- ### Uploading Files with upload Method in AngularFireStorage Source: https://github.com/angular/angularfire/blob/main/site/src/storage/getting-started.md Upload a file to Cloud Storage using the `upload` method directly on the `AngularFireStorage` service. This method simplifies the process and returns an `AngularFireUploadTask` for monitoring. ```typescript import { Component } from '@angular/core'; import { AngularFireStorage } from '@angular/fire/storage'; @Component({ selector: 'app-root', template: ` ` }) export class AppComponent { constructor(private storage: AngularFireStorage) { } uploadFile(event) { const file = event.target.files[0]; const filePath = 'name-your-file-path-here'; const task = this.storage.upload(filePath, file); } } ``` -------------------------------- ### Injecting and Using AngularFireAnalytics in Components Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Demonstrates how to dependency inject the `AngularFireAnalytics` service into an Angular component and use its methods, such as `logEvent`, to send analytics data. ```typescript import { AngularFireAnalytics } from '@angular/fire/analytics'; import { Component } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html' }) export class MyComponent { constructor(analytics: AngularFireAnalytics) { analytics.logEvent('custom_event', { ... }); } } ``` -------------------------------- ### Customizing Storage Bucket with BUCKET Token Source: https://github.com/angular/angularfire/blob/main/site/src/storage/getting-started.md Customize the storage bucket by providing a custom bucket name using the `BUCKET` injection token within your `NgModule`. This allows you to direct uploads to a specific bucket. ```typescript import { AngularFireStorageModule, BUCKET } from '@angular/fire/storage'; @NgModule({ providers: [ { provide: BUCKET, useValue: 'my-bucket-name' } ], ... }) export class AppModule {} ``` -------------------------------- ### Configuration with Dependency Injection Source: https://github.com/angular/angularfire/blob/main/docs/compat/analytics/getting-started.md Configure Google Analytics behavior using DI Tokens like `CONFIG` for general settings and `DEBUG_MODE` for enabling DebugView. ```APIDOC ## Configuration with Dependency Injection ### Configure Google Analytics with `CONFIG` - **Token**: `CONFIG` (default: `{}`) - **Description**: Allows configuration of Google Analytics settings. You can control options such as disabling the initial `page_view` event, anonymizing IP addresses, and disallowing ad personalization. #### Example: ```typescript import { AngularFireAnalyticsModule, CONFIG } from '@angular/fire/compat/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ { provide: CONFIG, useValue: { send_page_view: false, allow_ad_personalization_signals: false, anonymize_ip: true } } ] }) export class AppModule { } ``` Refer to the [gtag.js documentation](https://developers.google.com/analytics/devguides/collection/gtagjs/reference) for a comprehensive list of configuration options. ### Use DebugView `DEBUG_MODE` - **Token**: `DEBUG_MODE` (default: `false`) - **Description**: Set this token to `true` to enable [DebugView in Google Analytics](https://console.firebase.google.com/project/_/analytics/debugview), which allows you to see events in real-time. #### Example: ```typescript import { AngularFireAnalyticsModule, DEBUG_MODE } from '@angular/fire/compat/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ { provide: DEBUG_MODE, useValue: true } ] }) export class AppModule { } ``` ``` -------------------------------- ### Create New Angular Project using Yarn or NPM Source: https://github.com/angular/angularfire/blob/main/docs/install-and-setup.md These commands show how to create a new Angular project using either Yarn or NPM. It navigates into the newly created project directory. This step is essential for setting up the project structure before installing AngularFire. ```bash # Using yarn create yarn create @angular cd ``` ```bash # Using npm create npm create @angular cd ``` -------------------------------- ### Serve Angular App Locally Source: https://github.com/angular/angularfire/blob/main/docs/install-and-setup.md This command compiles and serves the Angular application locally. After running this, the application can be accessed via a web browser, typically at `http://localhost:4200/`. It's useful for development and testing. ```bash ng serve ``` -------------------------------- ### Install Firebase Tools as a Dev Dependency (npm, yarn) Source: https://github.com/angular/angularfire/blob/main/docs/install-firebase-tools.md Installs the Firebase CLI as a development dependency within your project. This is useful for project-specific tooling. Use `npx firebase` or `yarn firebase` to run commands. Requires Node.js and npm/yarn. ```bash npm install --save-dev firebase-tools ``` ```bash yarn add -D firebase-tools ``` -------------------------------- ### Deploy Angular App to Firebase Hosting Source: https://github.com/angular/angularfire/blob/main/docs/install-and-setup.md This command deploys the built Angular application to Firebase Hosting. Ensure that Firebase CLI is configured and logged in. This makes the application accessible on the web via a Firebase-provided URL. ```bash ng deploy ``` -------------------------------- ### Inject AngularFirestore in Angular Source: https://github.com/angular/angularfire/blob/main/site/src/get-started/quick-start.md Inject the AngularFirestore service into your Angular component. This service is essential for interacting with Firestore databases. Ensure you have `@angular/fire/firestore` installed. ```typescript import { Component, inject } from '@angular/core'; import { Firestore } from '@angular/fire/firestore'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.css'] }) export class AppComponent { private firestore: AngularFirestore = inject(Firestore) // ... } ``` -------------------------------- ### Import AngularFireMessaging Module Source: https://github.com/angular/angularfire/blob/main/site/src/messaging/getting-started.md This snippet shows how to import the AngularFireMessagingModule into your Angular application's root NgModule. This setup makes the AngularFireMessaging service available for dependency injection throughout your application. ```typescript import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { AngularFireModule } from '@angular/fire'; import { AngularFireMessagingModule } from '@angular/fire/messaging'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebase), AngularFireMessagingModule ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} ``` -------------------------------- ### Tracking Deployments with APP_NAME and APP_VERSION Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md This configuration allows tracking application version adoption by providing `APP_NAME` and `APP_VERSION` via DI tokens. This is useful for understanding how different versions of your PWA are used. ```typescript import { AngularFireAnalyticsModule, APP_NAME, APP_VERSION } from '@angular/fire/analytics'; import { AngularFireModule } from '@angular/fire'; import { environment } from '../environments/environment'; import { NgModule } from '@angular/core'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ { provide: APP_NAME, useValue: 'My PWA Name' }, { provide: APP_VERSION, useValue: '1.0.0' } ] }) export class AppModule { } ``` -------------------------------- ### Configure Firebase App in NgModule-based Angular Apps Source: https://github.com/angular/angularfire/blob/main/site/src/get-started/quick-start.md Initializes the Firebase app within an NgModule-based Angular application by adding the `provideFirebaseApp` provider to the `@NgModule` imports. This setup is essential for using any Firebase services. ```typescript import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, provideFirebaseApp(() => initializeApp(environment.firebase)), ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {} ``` -------------------------------- ### Trace Observable Until First Emission with NgRx traceUntilFirst Source: https://github.com/angular/angularfire/blob/main/docs/compat/performance/getting-started.md The `traceUntilFirst` operator measures the time until an observable emits its very first value. This is helpful for diagnosing delays in initial data retrieval or setup within an observable stream. ```typescript import { traceUntilFirst } from 'angular-ngrx-tools'; // Example: Measure time until the first data point is available initialDataObservable.pipe(traceUntilFirst('firstEmissionTrace')); ``` -------------------------------- ### Configuring Google Analytics with DI Tokens Source: https://github.com/angular/angularfire/blob/main/docs/compat/analytics/getting-started.md Customizes Google Analytics behavior using dependency injection tokens like CONFIG. This example shows how to disable the default page_view event, anonymize IP addresses, and disallow ad personalization. ```typescript import { AngularFireAnalyticsModule, CONFIG } from '@angular/fire/compat/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ { provide: CONFIG, useValue: { send_page_view: false, allow_ad_personalization_signals: false, anonymize_ip: true } } ] }) export class AppModule { } ``` -------------------------------- ### Polyfill First Input Delay (FID) in Angular Source: https://github.com/angular/angularfire/blob/main/docs/compat/performance/getting-started.md To accurately measure First Input Delay (FID), polyfill the browser performance API by installing the `first-input-delay` package and importing it into your `src/polyfills.ts`. This ensures consistent FID tracking across different browsers. ```bash npm install --save-dev first-input-delay ``` ```typescript import 'first-input-delay'; ``` -------------------------------- ### AngularFireAnalytics API Summary Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md This TypeScript code defines the interface for the `AngularFireAnalytics` class, including methods for logging events, setting user properties, and managing analytics collection. It also lists available injection tokens for configuration. ```typescript class AngularFireAnalytics { updateConfig(options: {[key:string]: any}): Promise; logEvent(eventName: string, eventParams?: {[key: string]: any}, options?: analytics.AnalyticsCallOptions): Promise; setCurrentScreen(screenName: string, options?: analytics.AnalyticsCallOptions): Promise; setUserId(id: string, options?: analytics.AnalyticsCallOptions): Promise; setUserProperties(properties: analytics.CustomParams, options?: analytics.AnalyticsCallOptions): Promise; setAnalyticsCollectionEnabled(enabled: boolean): Promise; app: Promise; } COLLECTION_ENABLED = InjectionToken; APP_VERSION = InjectionToken; APP_NAME = InjectionToken; DEBUG_MODE = InjectionToken; CONFIG = InjectionToken; ``` -------------------------------- ### Realtime Database Setup Source: https://github.com/angular/angularfire/blob/main/docs/database.md This snippet demonstrates how to set up the Realtime Database provider in your Angular application's configuration file. ```APIDOC ## Realtime Database Setup ### Description Ensure `AngularFire` is added to your project via `ng add @angular/fire`. Then, provide a Database instance in the application's `app.config.ts`. ### Method Configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; import { provideDatabase, getDatabase } from '@angular/fire/database'; export const appConfig: ApplicationConfig = { providers: [ provideFirebaseApp(() => initializeApp({ ... })), provideDatabase(() => getDatabase()), ... ], ... } ``` ### Response N/A ``` -------------------------------- ### Request Permission and Get Token in Angular Source: https://github.com/angular/angularfire/blob/main/site/src/messaging/getting-started.md Combines requesting notification permission with retrieving the user's FCM token using `requestPermission` and `tokenChanges` observables. This allows you to immediately get the token after permission is granted, which is necessary for sending notifications. The retrieved token should be saved to your backend. ```typescript import { Component } from '@angular/core'; import { AngularFireMessaging } from '@angular/fire/messaging'; import { mergeMapTo } from 'rxjs/operators'; @Component({ selector: 'app-root', template: ` ` }) export class AppComponent { constructor(private afMessaging: AngularFireMessaging) { } // Inject AngularFireMessaging service requestPermission() { this.afMessaging.requestPermission .pipe(mergeMapTo(this.afMessaging.tokenChanges)) // Switch to tokenChanges after permission is granted .subscribe( (token) => { console.log('Permission granted! Save to the server!', token); }, // Log token or save to backend (error) => { console.error(error); }, // Handle errors ); } } ``` -------------------------------- ### Initialize Firebase Emulators via CLI Source: https://github.com/angular/angularfire/blob/main/site/src/get-started/local-development.md This shell command launches the setup wizard for Firebase emulators. After running `firebase init`, this command helps you select and configure the specific emulators you wish to use for local development. ```shell firebase init emulators ``` -------------------------------- ### Trace Observable While Condition Met with traceWhile() Source: https://github.com/angular/angularfire/blob/main/site/src/performance/getting-started.md The `traceWhile` operator traces an observable starting from an emission that passes a test condition, continuing until an emission fails the test. The `orComplete` option ensures tracing completes if the observable finishes. ```typescript traceWhile( name: string, test: (T) => Boolean, options?: { orComplete?: true } ) ``` -------------------------------- ### User Tracking Service Source: https://github.com/angular/angularfire/blob/main/site/src/analytics/getting-started.md Automatically tracks the currently signed-in user by setting `setUserId` and `setUserProperties`. ```APIDOC ## Tracking User Identifiers ### Integrating UserTrackingService ```typescript import { AngularFireAnalyticsModule, UserTrackingService } from '@angular/fire/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ UserTrackingService ] }) export class AppModule { } ``` `AngularFireAnalyticsModule` will initialize `UserTrackingService` if it is provided. This service dynamically imports `firebase/auth`, monitors for changes in the logged in user, and calls `setUserId` for you automatically. ``` -------------------------------- ### Manual Trace Implementation with AngularFirePerformance Source: https://github.com/angular/angularfire/blob/main/docs/compat/performance/getting-started.md Manually track custom operations or code blocks using `AngularFirePerformance`. Inject the `AngularFirePerformance` service and use its `trace` method to start and stop custom traces for detailed performance analysis. ```typescript constructor(private performance: AngularFirePerformance) {} ... const trace = await this.performance.trace('some-trace'); trace.start(); ... trace.stop(); ``` -------------------------------- ### Monitor AngularFire Upload Percentage and Download URL Source: https://github.com/angular/angularfire/blob/main/site/src/storage/getting-started.md Observes the upload completion percentage and retrieves the download URL for a file uploaded using AngularFireStorage. It uses RxJS operators like `finalize` to process the upload task. ```typescript import { finalize } from 'rxjs/operators'; @Component({ selector: 'app-root', template: `{%raw%}
{{ uploadPercent | async }}
{{ downloadURL | async }} {%endraw%}` }) export class AppComponent { uploadPercent: Observable; downloadURL: Observable; constructor(private storage: AngularFireStorage) {} uploadFile(event) { const file = event.target.files[0]; const filePath = 'name-your-file-path-here'; const fileRef = this.storage.ref(filePath); const task = this.storage.upload(filePath, file); // observe percentage changes this.uploadPercent = task.percentageChanges(); // get notified when the download URL is available task.snapshotChanges().pipe( finalize(() => this.downloadURL = fileRef.getDownloadURL() ) ) .subscribe() } } ``` -------------------------------- ### Trace Observable While Condition Holds with NgRx traceWhile Source: https://github.com/angular/angularfire/blob/main/docs/compat/performance/getting-started.md The `traceWhile` operator traces an observable starting from an emission that passes a test, and continues until an emission fails the test. The `orComplete` option ensures tracing concludes if the observable completes before the condition fails. Useful for logging sequences. ```typescript import { traceWhile } from 'angular-ngrx-tools'; // Example: Trace while values are less than 5 myObservable.pipe( traceWhile('traceWhileExample', (value) => value < 5) ); // Example: Trace while values are valid or until completion myObservable.pipe( traceWhile('traceWhileOrComplete', (value) => isValid(value), { orComplete: true }) ); ``` -------------------------------- ### Inject AngularFireFunctions Service Source: https://github.com/angular/angularfire/blob/main/site/src/functions/getting-started.md Once AngularFireFunctionsModule is registered, you can inject the AngularFireFunctions service into your components or services. This allows you to interact with Cloud Functions from your Angular app. ```typescript import { Component } from '@angular/core'; import { AngularFireFunctions } from '@angular/fire/functions'; @Component({ selector: 'app-component', template: `` }) export class AppComponent { constructor(private fns: AngularFireFunctions) { } } ``` -------------------------------- ### Initialize AngularFireModule in AppModule Source: https://github.com/angular/angularfire/blob/main/site/src/ionic/getting-started.md Configures the `AngularFireModule` within the main application module (`app.module.ts`) by initializing it with the Firebase configuration. Imports `AngularFireModule` and `firebaseConfig`. ```typescript import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { MyApp } from './app.component'; import { AngularFireModule } from '@angular/fire'; import { firebaseConfig } from '../environment'; @NgModule({ declarations: [ MyApp ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), AngularFireModule.initializeApp(firebaseConfig) ], bootstrap: [IonicApp], }) export class AppModule {} ``` -------------------------------- ### Install AngularFire and Firebase in Angular Project Source: https://context7.com/angular/angularfire/llms.txt This snippet shows the command-line steps to create a new Angular project and then add AngularFire and Firebase using the Angular CLI. It ensures the necessary packages are installed and configured for the project. ```bash # Create new Angular project ng add @angular/fire ``` -------------------------------- ### Screen Tracking Service Source: https://github.com/angular/angularfire/blob/main/docs/compat/analytics/getting-started.md The ScreenTrackingService automatically integrates with the Angular Router to provide automatic screen view tracking to Firebase Analytics. ```APIDOC ## Service: ScreenTrackingService ### Description Automatically logs `screen_view` events by integrating with the Angular Router. ### Usage Provide `ScreenTrackingService` in your `AppModule` to enable automatic screen view tracking. ```typescript import { AngularFireAnalyticsModule, ScreenTrackingService } from '@angular/fire/compat/analytics'; @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebase), AngularFireAnalyticsModule ], providers: [ ScreenTrackingService ] }) export class AppModule { } ``` ### Automatic Initialization `AngularFireAnalyticsModule` will initialize `ScreenTrackingService` if it is provided. ``` -------------------------------- ### Install mkdir-recursive Dependency (Bash) Source: https://github.com/angular/angularfire/blob/main/docs/universal/prerendering.md Installs the `mkdir-recursive` package as a development dependency. This utility is used to create directories recursively, which is needed for organizing the prerendered static files in the correct folder structure. ```bash npm i --save-dev mkdir-recursive ``` -------------------------------- ### Trace Observable Until First Emission with traceUntilFirst() Source: https://github.com/angular/angularfire/blob/main/site/src/performance/getting-started.md The `traceUntilFirst` operator traces an observable only until its very first emission occurs. This is useful for measuring the latency of the initial data retrieval. ```typescript traceUntilFirst(name: string) ```