diff --git a/README.md b/README.md index bc81231f2..76b500d27 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ export class AppModule { } ``` ```ts +import { inject } from '@angular/core'; import { Firestore, collectionData, collection } from '@angular/fire/firestore'; import { Observable } from 'rxjs'; @@ -51,8 +52,10 @@ interface Item { }) export class AppComponent { item$: Observable; - constructor(firestore: Firestore) { - const collection = collection(firestore, 'items'); + firestore: Firestore = inject(Firestore); + + constructor() { + const itemCollection = collection(this.firestore, 'items'); this.item$ = collectionData(collection); } } @@ -116,86 +119,97 @@ Get help on our [Q&A board](https://github.com/angular/angularfire/discussions?d ## Developer Guide -AngularFire has a new tree-shakable API, however this is still under active development and documentation is in the works, so we suggest most developers stick with the Compatiability API for the time being. [See the v7 upgrade guide for more information.](docs/version-7-upgrade.md). - -This developer guide assumes you're using the Compatiability API (`@angular/fire/compat/*`). - -### Monitor usage of your application in production - -> `AngularFireAnalytics` provides a convenient method of interacting with Google Analytics in your Angular application. The provided `ScreenTrackingService` and `UserTrackingService` automatically log events when you're using the Angular Router or Firebase Authentication respectively. [Learn more about Google Analytics](https://firebase.google.com/docs/analytics). - -- [Getting started with Google Analytics](docs/analytics/getting-started.md) - -### Interacting with your database(s) - -Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing. [Learn about the differences between them in the Firebase Documentation](https://firebase.google.com/docs/firestore/rtdb-vs-firestore). - -#### Cloud Firestore - -> `AngularFirestore` allows you to work with Cloud Firestore, the new flagship database for mobile app development. It improves on the successes of Realtime Database with a new, more intuitive data model. Cloud Firestore also features richer, faster queries and scales better than Realtime Database. - -- [Documents](docs/firestore/documents.md) -- [Collections](docs/firestore/collections.md) -- [Querying Collections](docs/firestore/querying-collections.md) -- [Offline data](docs/firestore/offline-data.md) - -#### Realtime Database - -> `AngularFireDatabase` allows you to work with the Realtime Database, Firebase's original database. It's an efficient, low-latency solution for mobile apps that require synced states across clients in realtime. - -- [Objects](docs/rtdb/objects.md) -- [Lists](docs/rtdb/lists.md) -- [Querying lists](docs/rtdb/querying-lists.md) - -### Authenticate users - -- [Getting started with Firebase Authentication](docs/auth/getting-started.md) -- [Route users with AngularFire guards](docs/auth/router-guards.md) - -### Local Emulator Suite - -- [Getting started with Firebase Emulator Suite](docs/emulators/emulators.md) - -### Upload files - -- [Getting started with Cloud Storage](docs/storage/storage.md) - -### Receive push notifications - -- [Getting started with Firebase Messaging](docs/messaging/messaging.md) +This developer guide assimes you're using the new tree-shakable AngularFire API, [if you're looking for the compatability API you can find the documentation here](docs/compat.md). -### **BETA:** Change behavior and appearance of your application without deploying +[See the v7 upgrade guide for more information on this change.](docs/version-7-upgrade.md). -> Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update. [Learn more about Remote Config](https://firebase.google.com/docs/remote-config). +### Firebase product integrations -- [Getting started with Remote Config](docs/remote-config/getting-started.md) + + + + + + + + + + + + + + + + + + + + + +
-### Monitor your application performance in production - -> Firebase Performance Monitoring is a service that helps you to gain insight into the performance characteristics of your iOS, Android, and web apps. [Learn more about Performance Monitoring](https://firebase.google.com/docs/perf-mon). +#### [Analytics](docs/analytics.md#analytics) +```ts +import { } from '@angular/fire/analytics'; +``` + -- [Getting started with Performance Monitoring](docs/performance/getting-started.md) +#### [Authentication](docs/auth.md#authentication) +```ts +import { } from '@angular/fire/auth'; +``` +
-### Directly call Cloud Functions +#### [Cloud Firestore](docs/firestore.md#cloud-firestore) +```ts +import { } from '@angular/fire/firestore'; +``` + -- [Getting started with Callable Functions](docs/functions/functions.md) +#### [Cloud Functions](docs/functions.md#cloud-functions) +```ts +import { } from '@angular/fire/functions'; +``` +
-### Deploying your application +#### [Cloud Messaging](docs/messaging.md#cloud-messaging) +```ts +import { } from '@angular/fire/messaging'; +``` + -> Firebase Hosting is production-grade web content hosting for developers. With Hosting, you can quickly and easily deploy web apps and static content to a global content delivery network (CDN) with a single command. +#### [Cloud Storage](docs/storage.md#cloud-storage) +```ts +import { } from '@angular/fire/storage'; +``` +
-- [Deploy your application on Firebase Hosting](docs/deploy/getting-started.md) +#### [Performance Monitoring](docs/performance.md#performance-monitoring) +```ts +import { } from '@angular/fire/performance'; +``` + -#### Server-side rendering +#### [Realtime Database](docs/database.md#realtime-database) +```ts +import { } from '@angular/fire/database'; +``` +
-> Angular Universal is a technology that allows you to run your Angular application on a server. This allows you to generate your HTML in a process called server-side rendering (SSR). AngularFire is compatible with server-side rendering; allowing you to take advantage of the Search Engine Optimization, link previews, the performance gains granted by the technology, and more. [Learn more about Angular Universal](https://angular.io/guide/universal). +#### [Remote Config](docs/remote-config.md#remote-config) +```ts +import { } from '@angular/fire/remote-config'; +``` + -- [Getting started with Angular Universal](docs/universal/getting-started.md) -- [Deploying your Universal application on Cloud Functions for Firebase](docs/universal/cloud-functions.md) -- [Prerendering your Universal application](docs/universal/prerendering.md) +#### [App Check](docs/app-check.md#app-check) +```ts +import { } from '@angular/fire/app-check'; +``` +
-### Ionic +### Deploying your site -- [Installation and Setup with Ionic CLI](docs/ionic/cli.md) -- [Using AngularFire with Ionic 2](docs/ionic/v2.md) -- [Using AngularFire with Ionic 3](docs/ionic/v3.md) +* Deploy to Firebase Hosting +* Angular Universal: Deploy to Cloud Functions +* Angular Universal: Deploy to Cloud Run diff --git a/docs/analytics.md b/docs/analytics.md new file mode 100644 index 000000000..2269b2666 --- /dev/null +++ b/docs/analytics.md @@ -0,0 +1,67 @@ + + + +AngularFireDeveloper Guide ❱ Analytics + + +# Analytics + +Google Analytics is an app measurement solution, available at no charge, that provides insight on app usage and user engagement. + +[Learn more](https://firebase.google.com/docs/analytics) +## Dependency Injection + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide a Google Analytics instance in the application's `NgModule` (`app.module.ts`): + +```ts +@NgModule({ + declarations: [ + ... + ], + imports: [ + ... + // App initialization + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideAnalytics(() => getAnalytics()) + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } +``` + +In your component class, for example `user-profile.component.ts` import and inject `Firestore`: + +```typescript +import { Component, inject } from '@angular/core'; +import { Analytics } from '@angular/fire/analytics'; + +@Component({ + standalone: true, + selector: 'app-user-profile', + ... +}) +export class UserProfileComponent { + private analytics: Analytics = inject(Analytics); + ... +} +``` + +## Firebase API + +The [Firebase API for Google Analytics documentation](https://firebase.google.com/docs/reference/js/analytics.md#analytics_package) is available on the Firebase website. + +## Services + +### ScreenTrackingService + +Coming soon, for now [please review the documentation](https://firebase.google.com/docs/analytics/screenviews) + +### UserTrackingService +Coming soon + diff --git a/docs/app-check.md b/docs/app-check.md new file mode 100644 index 000000000..272bd7760 --- /dev/null +++ b/docs/app-check.md @@ -0,0 +1,53 @@ + +AngularFireDeveloper Guide ❱ Realtime App Check + + + + +# App Check + +App Check helps protect your API resources from abuse by preventing unauthorized clients from accessing your backend resources. It works with both Firebase services, Google Cloud services, and your own APIs to keep your resources safe. + +[Learn More](https://firebase.google.com/docs/app-check) + +## Dependency Injection +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide an App Check instance and configuration in the application's `NgModule` (`app.module.ts`): + +```ts +import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; +import { getAppCheck, provideAppCheck } from '@angular/fire/app-check'; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideAppCheck(() => initializeAppCheck(getApp(), { + provider: new ReCaptchaV3Provider(/* configuration */), + })), + ] +}) +``` + +Next inject it into your component: + +```ts +import { Component, inject} from '@angular/core'; +import { AppCheck } from '@angular/fire/app-check'; + +@Component({ ... }) +export class AppCheckComponent { + private appCheck: AppCheck = inject(AppCheck); + ... +} +``` + +## Firebase API + +The [AppCheck documentation](https://firebase.google.com/docs/reference/js/app-check) is available on the Firebase website. + +## Convenience observables +Coming soon. \ No newline at end of file diff --git a/docs/auth.md b/docs/auth.md new file mode 100644 index 000000000..120920a4c --- /dev/null +++ b/docs/auth.md @@ -0,0 +1,165 @@ + + + +AngularFireDeveloper Guide ❱ Authentication + + +# Authentication + +Most apps need to know the identity of a user. Knowing a user's identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user's devices. +Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more. + +Firebase Authentication integrates tightly with other Firebase services, and it leverages industry standards like OAuth 2.0 and OpenID Connect, so it can be easily integrated with your custom backend. + +[Learn more about Firebase Authentication](https://firebase.google.com/docs/auth) + +## Dependency Injection + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide an auth instance in the application's `NgModule` (`app.module.ts`): + +```ts +import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; +import { getAuth, provideAuth } from '@angular/fire/auth'; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideAuth(() => getAuth()), + ] +}) +``` + +Next inject it into your component: + +```ts +import { Component, inject} from '@angular/core'; +import { Auth } from '@angular/fire/auth'; + +@Component({ ... }) +export class LoginComponent { + private auth: Auth = inject(Auth); + ... +} +``` + +## Firebase API + +AngularFire wraps the Firebase JS SDK to ensure proper functionality in Angular, while providing the same API. + +Update the imports from `import { ... } from 'firebase/auth'` to `import { ... } from '@angular/fire/auth'` and follow the offical documentation. + +[Getting Started](https://firebase.google.com/docs/auth/web/start) | [API Reference](https://firebase.google.com/docs/reference/js/auth) + +## Convenience observables + +AngularFire provides observables to allow convenient use of the Firebase Authentication with RXJS. + +### user + +The `user` observable streams events triggered by sign-in, sign-out, and token refresh events. + +Example code: + +```ts +import { Auth, User, user } from '@angular/fire/auth'; +... + +export class UserComponent implements OnDestroy { + private auth: Auth = inject(auth); + user$ = user(auth); + userSubscription: Subscription; + ... + + constructor() { + this.userSubscription = this.user$.subscribe(aUser: User | null => { + //handle user state changes here. Note, that user will be null if there is no currently logged in user. + console.log(aUser); + }) + } + + ngOnDestroy() { + // when manually subscribing to an observable remember to unsubscribe in ngOnDestroy + this.userSubscription.unsubscribe(); + } +} + +``` + +### authState + +The `authState` observable streams events triggered by sign-in and sign-out events. + +Example code: +```ts +import { Auth, authState } from '@angular/fire/auth'; +... + +export class UserComponent implements OnDestroy { + private auth: Auth = inject(auth); + authState$ = authState(auth); + authStateSubscription: Subscription; + ... + + constructor() { + this.authStateSubscription = this.authState$.subscribe((aUser: User | null) => { + //handle auth state changes here. Note, that user will be null if there is no currently logged in user. + console.log(aUser); + }) + } + + ngOnDestroy() { + // when manually subscribing to an observable remember to unsubscribe in ngOnDestroy + this.authStateSubscription.unsubscribe(); + } +} +``` + +### idToken + +The `idToken` observable streams events triggered by sign-in, sign-out and token refresh events. + +Example code: +```ts +import { Auth, idToken } from '@angular/fire/auth'; +... + +export class UserComponent implements OnDestroy { + private auth: Auth = inject(auth); + idToken$ = idToken(auth); + idTokenSubscription: Subscription; + ... + + constructor() { + this.idTokenSubscription = this.idToken$.subscribe((token: string | null) => { + //handle idToken changes here. Note, that user will be null if there is no currently logged in user. + console.log(string); + }) + } + + ngOnDestroy() { + // when manually subscribing to an observable remember to unsubscribe in ngOnDestroy + this.idTokenSubscription.unsubscribe(); + } +} +``` + +## Connecting the the emulator suite + +```ts +import { connectAuthEmulator, getAuth, provideAuth } from '@angular/fire/auth'; + +@NgModule({ + imports: [ + provideAuth(() => { + const auth = getAuth(); + connectAuthEmulator(auth, 'http://localhost:9099', { disableWarnings: true }); + return auth; + }), + ] +}) +``` \ No newline at end of file diff --git a/docs/compat.md b/docs/compat.md new file mode 100644 index 000000000..221c8507a --- /dev/null +++ b/docs/compat.md @@ -0,0 +1,70 @@ +# AngularFire +The official [Angular](https://angular.io/) library for [Firebase](https://firebase.google.com/). + +
ng add @angular/fire
+ +## Compatibility Developer Guide + +AngularFire has a new tree-shakable API, you're looking at the documentation for the compatability version of the library. [Find the new developer guide here](../README.md#developer-guide). + +[See the v7 upgrade guide for more information on this change.](version-7-upgrade.md). + +### Monitor usage of your application in production + +> `AngularFireAnalytics` provides a convenient method of interacting with Google Analytics in your Angular application. The provided `ScreenTrackingService` and `UserTrackingService` automatically log events when you're using the Angular Router or Firebase Authentication respectively. [Learn more about Google Analytics](https://firebase.google.com/docs/analytics). + +- [Getting started with Google Analytics](compat/analytics/getting-started.md) + +### Interacting with your database(s) + +Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing. [Learn about the differences between them in the Firebase Documentation](https://firebase.google.com/docs/firestore/rtdb-vs-firestore). + +#### Cloud Firestore + +> `AngularFirestore` allows you to work with Cloud Firestore, the new flagship database for mobile app development. It improves on the successes of Realtime Database with a new, more intuitive data model. Cloud Firestore also features richer, faster queries and scales better than Realtime Database. + +- [Documents](compat/firestore/documents.md) +- [Collections](compat/firestore/collections.md) +- [Querying Collections](compat/firestore/querying-collections.md) +- [Offline data](compat/firestore/offline-data.md) + +#### Realtime Database + +> `AngularFireDatabase` allows you to work with the Realtime Database, Firebase's original database. It's an efficient, low-latency solution for mobile apps that require synced states across clients in realtime. + +- [Objects](compat/rtdb/objects.md) +- [Lists](compat/rtdb/lists.md) +- [Querying lists](compat/rtdb/querying-lists.md) + +### Authenticate users + +- [Getting started with Firebase Authentication](acompat/uth/getting-started.md) +- [Route users with AngularFire guards](compat/auth/router-guards.md) + +### Local Emulator Suite + +- [Getting started with Firebase Emulator Suite](compat/emulators/emulators.md) + +### Upload files + +- [Getting started with Cloud Storage](compat/storage/storage.md) + +### Receive push notifications + +- [Getting started with Firebase Messaging](compat/messaging/messaging.md) + +### **BETA:** Change behavior and appearance of your application without deploying + +> Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update. [Learn more about Remote Config](https://firebase.google.com/docs/remote-config). + +- [Getting started with Remote Config](compat/remote-config/getting-started.md) + +### Monitor your application performance in production + +> Firebase Performance Monitoring is a service that helps you to gain insight into the performance characteristics of your iOS, Android, and web apps. [Learn more about Performance Monitoring](https://firebase.google.com/docs/perf-mon). + +- [Getting started with Performance Monitoring](compat/performance/getting-started.md) + +### Directly call Cloud Functions + +- [Getting started with Callable Functions](compat/functions/functions.md) diff --git a/docs/analytics/getting-started.md b/docs/compat/analytics/getting-started.md similarity index 95% rename from docs/analytics/getting-started.md rename to docs/compat/analytics/getting-started.md index 2a1bedda2..3c5af8aaf 100644 --- a/docs/analytics/getting-started.md +++ b/docs/compat/analytics/getting-started.md @@ -2,6 +2,8 @@ `AngularFireAnalytics` dynamically imports the `firebase/analytics` library and provides a promisified version of the [Firebase Analytics SDK (`firebase.analytics.Analytics`)](https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics.html). +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ### API: ```ts diff --git a/docs/auth/getting-started.md b/docs/compat/auth/getting-started.md similarity index 94% rename from docs/auth/getting-started.md rename to docs/compat/auth/getting-started.md index f5716474d..7bbbb7a30 100644 --- a/docs/auth/getting-started.md +++ b/docs/compat/auth/getting-started.md @@ -6,6 +6,8 @@ `firebase.auth.Auth` instance, allowing you to log users in, out, etc. [See the Firebase docs for more information on what methods are available.](https://firebase.google.com/docs/reference/js/firebase.auth.Auth) +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + **Example app:** ```ts diff --git a/docs/auth/router-guards.md b/docs/compat/auth/router-guards.md similarity index 94% rename from docs/auth/router-guards.md rename to docs/compat/auth/router-guards.md index a1d5cf28f..efce40b59 100644 --- a/docs/auth/router-guards.md +++ b/docs/compat/auth/router-guards.md @@ -2,6 +2,8 @@ `AngularFireAuthGuard` provides a prebuilt [`canActivate` Router Guard](https://angular.io/api/router/CanActivate) using `AngularFireAuth`. By default unauthenticated users are not permitted to navigate to protected routes: +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ```ts import { AngularFireAuthGuard } from '@angular/fire/compat/auth-guard'; diff --git a/docs/emulators/emulators.md b/docs/compat/emulators/emulators.md similarity index 95% rename from docs/emulators/emulators.md rename to docs/compat/emulators/emulators.md index 1dbf0c450..3a6b88e32 100644 --- a/docs/emulators/emulators.md +++ b/docs/compat/emulators/emulators.md @@ -2,6 +2,8 @@ In this guide, we'll look at how to use `@angular/fire` to connect an Angular application with Firebase Emulator Suite to start prototyping your apps. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + There are four supported emulators, all of them available at the Firebase suite workflow: - [Authentication Emulator](https://firebase.google.com/docs/emulator-suite/connect_auth) diff --git a/docs/firestore/collections.md b/docs/compat/firestore/collections.md similarity index 97% rename from docs/firestore/collections.md rename to docs/compat/firestore/collections.md index 6b17d6ac7..4b6dbd1e5 100644 --- a/docs/firestore/collections.md +++ b/docs/compat/firestore/collections.md @@ -3,6 +3,8 @@ > Cloud Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in *documents*, which are organized into *collections*. Each *document* contains a set of key-value pairs. Cloud Firestore is optimized for storing large collections of small documents. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ## Using `AngularFirestoreCollection` The `AngularFirestoreCollection` service is a wrapper around the native Firestore SDK's [`CollectionReference`](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) and [`Query`](https://firebase.google.com/docs/reference/js/firebase.firestore.Query) types. It is a generic service that provides you with a strongly typed set of methods for manipulating and streaming data. This service is designed for use as an `@Injectable()`. diff --git a/docs/firestore/documents.md b/docs/compat/firestore/documents.md similarity index 94% rename from docs/firestore/documents.md rename to docs/compat/firestore/documents.md index fdadc04c9..c59624685 100644 --- a/docs/firestore/documents.md +++ b/docs/compat/firestore/documents.md @@ -3,6 +3,8 @@ > Cloud Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in *documents*, which are organized into *collections*. Each *document* contains a set of key-value pairs. Cloud Firestore is optimized for storing large collections of small documents. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ## Using `AngularFirestoreDocument` The `AngularFirestoreDocument` service is a wrapper around the native Firestore SDK's [`DocumentReference` type](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference). It is a generic service that provides you with a strongly typed set of methods for manipulating and streaming data. This service is designed for use as an `@Injectable()`. diff --git a/docs/firestore/offline-data.md b/docs/compat/firestore/offline-data.md similarity index 89% rename from docs/firestore/offline-data.md rename to docs/compat/firestore/offline-data.md index 6619e73f8..3e16b845c 100644 --- a/docs/firestore/offline-data.md +++ b/docs/compat/firestore/offline-data.md @@ -2,6 +2,8 @@ > Cloud Firestore supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data. When the device comes back online, Cloud Firestore synchronizes any local changes made by your app to the data stored remotely in Cloud Firestore. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + **Offline persistence is an experimental feature that is supported only by the Chrome, Safari, and Firefox web browsers.** If a user opens multiple browser tabs that point to the same Cloud Firestore database, and offline persistence is enabled, Cloud Firestore will work correctly only in the first tab. ## Enable Offline Data in AngularFirestore diff --git a/docs/firestore/querying-collections.md b/docs/compat/firestore/querying-collections.md similarity index 96% rename from docs/firestore/querying-collections.md rename to docs/compat/firestore/querying-collections.md index c80eed75e..0ea89a071 100644 --- a/docs/firestore/querying-collections.md +++ b/docs/compat/firestore/querying-collections.md @@ -3,6 +3,8 @@ > Firestore has [powerful querying syntax](https://firebase.google.com/docs/firestore/query-data/queries) and the `AngularFirestoreCollection` provides a thin wrapper around it. This keeps you from having to learn two query syntax systems. If you know the [Firestore query API](https://firebase.google.com/docs/reference/js/firebase.firestore.Query) then you know how to query in AngularFirestore. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ## Creating a query with primitive/scalar values Queries are created by building on the [`firebase.firestore.CollectionReference`](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference). diff --git a/docs/functions/functions.md b/docs/compat/functions/functions.md similarity index 94% rename from docs/functions/functions.md rename to docs/compat/functions/functions.md index d6a2f7c39..708788ca7 100644 --- a/docs/functions/functions.md +++ b/docs/compat/functions/functions.md @@ -2,6 +2,8 @@ > The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ### Import the `NgModule` Cloud Functions for AngularFire is contained in the `@angular/fire/functions` module namespace. Import the `AngularFireFunctionsModule` in your `NgModule`. This sets up the `AngularFireFunction` service for dependency injection. diff --git a/docs/messaging/messaging.md b/docs/compat/messaging/messaging.md similarity index 97% rename from docs/messaging/messaging.md rename to docs/compat/messaging/messaging.md index 5ad10a531..593e59003 100644 --- a/docs/messaging/messaging.md +++ b/docs/compat/messaging/messaging.md @@ -2,6 +2,8 @@ > The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ### AngularFireMessaging is not out-of-the-box compatible with the Angular Service Worker If you are using the Angular Service Worker, you are not currently able to use AngularFireMessaging out-of-the-box. diff --git a/docs/performance/getting-started.md b/docs/compat/performance/getting-started.md similarity index 95% rename from docs/performance/getting-started.md rename to docs/compat/performance/getting-started.md index c63863e3a..c435693bf 100644 --- a/docs/performance/getting-started.md +++ b/docs/compat/performance/getting-started.md @@ -1,5 +1,7 @@ # Getting started with Performance Monitoring +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ## Automatic page load tracing Understand your Angular application's real-world performance with [Firebase Performance Monitoring](https://firebase.google.com/docs/perf-mon). Performance Monitoring automatically provides a trace for **page load** when you add `AngularFirePerformanceModule` into your App Module's imports. diff --git a/docs/remote-config/getting-started.md b/docs/compat/remote-config/getting-started.md similarity index 95% rename from docs/remote-config/getting-started.md rename to docs/compat/remote-config/getting-started.md index eb03c3880..ab4bfa049 100644 --- a/docs/remote-config/getting-started.md +++ b/docs/compat/remote-config/getting-started.md @@ -2,6 +2,8 @@ `AngularFireRemoteConfig` dynamically imports the `firebase/remote-config` library on demand, provides convenience observables, pipes, and a promisified version of the [Firebase Remote Config SDK (`firebase.remoteConfig.RemoteConfig`)](https://firebase.google.com/docs/reference/js/firebase.remoteconfig.RemoteConfig). +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ### API: ```ts diff --git a/docs/rtdb/lists.md b/docs/compat/rtdb/lists.md similarity index 97% rename from docs/rtdb/lists.md rename to docs/compat/rtdb/lists.md index a63139d9b..084c54eeb 100644 --- a/docs/rtdb/lists.md +++ b/docs/compat/rtdb/lists.md @@ -1,5 +1,7 @@ # 3. Retrieving data as lists +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + > AngularFire synchronizes data as lists using the `AngularFireList` service. The `AngularFireList` service is not created by itself, but through the `AngularFireDatabase` service. diff --git a/docs/rtdb/objects.md b/docs/compat/rtdb/objects.md similarity index 95% rename from docs/rtdb/objects.md rename to docs/compat/rtdb/objects.md index 766b7e345..76c9725ee 100644 --- a/docs/rtdb/objects.md +++ b/docs/compat/rtdb/objects.md @@ -1,5 +1,7 @@ # 2. Retrieving data as objects +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + > The `AngularFireObject` is a service for manipulating and streaming object data. The `AngularFireObject` service is not created by itself, but through the `AngularFireDatabase` service. diff --git a/docs/rtdb/querying-lists.md b/docs/compat/rtdb/querying-lists.md similarity index 95% rename from docs/rtdb/querying-lists.md rename to docs/compat/rtdb/querying-lists.md index d4be3c8d9..1279d800c 100644 --- a/docs/rtdb/querying-lists.md +++ b/docs/compat/rtdb/querying-lists.md @@ -1,5 +1,7 @@ # 4. Querying lists +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ## Creating a query with primitive/scalar values Queries are created by building on the [`firebase.database.Reference`](https://firebase.google.com/docs/reference/js/firebase.database.Reference). diff --git a/docs/storage/storage.md b/docs/compat/storage/storage.md similarity index 96% rename from docs/storage/storage.md rename to docs/compat/storage/storage.md index 202f42e51..867805041 100644 --- a/docs/storage/storage.md +++ b/docs/compat/storage/storage.md @@ -2,6 +2,8 @@ > Cloud Storage is designed to help you quickly and easily store and serve user-generated content, such as photos and videos. +> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md). + ### Import the `NgModule` Cloud Storage for AngularFire is contained in the `@angular/fire/storage` module namespace. Import the `AngularFireStorageModule` in your `NgModule`. This sets up the `AngularFireStorage` service for dependency injection. diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 000000000..0016192d1 --- /dev/null +++ b/docs/database.md @@ -0,0 +1,175 @@ + + + +AngularFireDeveloper Guide ❱ Realtime Database + + +# Realtime Database + +Store and sync data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available when your app goes offline. + +The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data. [Learn more about the Realtime Database](https://firebase.google.com/docs/database). + +## Dependency Injection + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide an RTBD instance in the application's `NgModule` (`app.module.ts`): + +```ts +import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; +import { getDatabase, provideDatabase } from '@angular/fire/database'; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideDatabase(() => getDatabase()), + ] +}) +``` + +Next inject it into your component: + +```ts +import { Component, inject } from '@angular/core'; +import { Database } from '@angular/fire/database'; + +@Component({...}) +extend class DepartmentComponent { + private database: Database = inject(Database); + + constructor() { + } +} +``` + +## Firebase API + +AngularFire wraps the Firebase JS SDK to ensure proper functionality in Angular, while providing the same API. + +Just change your imports from `import { ... } from 'firebase/database'` to `import { ... } from '@angular/fire/database'` and follow the offical documentation. + +[Getting Started](https://firebase.google.com/docs/database/web/start) | [API Reference](https://firebase.google.com/docs/reference/js/database) + +## Convenience observables + +AngularFire provides observables to allow convenient use of the Realtime Database with RXJS. + +### `object` + +The `object()` function creates an observable that emits object changes. + +| | | +|-----------------|------------------------------------------| +| **function** | `object(ref)` | +| **params** | ref: `Reference` | +| **return** | `Observable` | + +### `objectVal` + +The `objectVal` function creates an observable that emits an array of object values, optionally with a mapped key. + +| | | +|-----------------|-------------------------------------------------------| +| **function** | `objectVal(query, options?)` | +| **params** | query: `Reference\|Query`, options?: { keyField?: `string` } | +| **return** | `Observable` | + +### `list` + +The `list()` function creates an observable that emits a sorted array for each child event change. The optional `events` parameter will filter which child events populate the array. + +| | | +|-----------------|-------------------------------------------------------| +| **function** | `list(ref, options?)` | +| **params** | ref: `Reference\|Query`, options?: { events?: `ListenEvent[]` } | +| **return** | `Observable` | + +### `listVal` + +The `listVal()` function creates an observable that emits an object mapped to its value, and optionally its key. + +| | | +|-----------------|-------------------------------------------------------| +| **function** | `listVal(query, options?)` | +| **params** | ref: `Reference\|Query`, options?: { keyField?: `string` } | +| **return** | `Observable` | + +### `stateChanges` + +The `stateChanges()` function creates an observable that emits each time a change occurs at the reference or query passed. This is useful for tracking the changes in your list. The optional `events` parameter will filter which child events populate the array. + +| | | +|-----------------|------------------------------------------------------| +| **function** | `stateChanges(ref, options?)` | +| **params** | ref: `Reference\|Query`, options:? { events?: `ListenEvent[]` } | +| **return** | `Observable` | + +### `auditTrail` + +The `auditTrail()` function creates an observable that emits the entire state trail. This is useful for debugging or replaying the state of a list in your app. The optional `events` parameter will filter which child events populate the array. + +| | | +|-----------------|------------------------------------------------------| +| **function** | `auditTrail(ref, options?)` | +| **params** | ref: `Reference\|Query`, options?: { events?: `ListenEvent[]` } | +| **return** | `Observable` | + +### `fromRef` + +The `fromRef()` function creates an observable that emits reference changes. + +| | | +|-----------------|------------------------------------------| +| **function** | `fromRef(ref, event)` | +| **params** | ref: `Reference\|Query`, event: `ListenEvent` | +| **return** | `Observable` | + +## Connecting the the emulator suite + +```ts +import { connectDatabaseEmulator, getDatabase, provideDatabase } from '@angular/fire/database'; + +@NgModule({ + imports: [ + provideDatabase(() => { + const database = getDatabase(); + connectDatabaseEmulator(database, 'localhost', 9000); + return database; + }), + ] +}) +``` + +## Working with multiple instances + +```ts +import { provideFirebaseApp, FirebaseApp, initializeApp } from '@angular/fire/app'; +import { getDatabase, provideDatabase } from '@angular/fire/database'; + +const DATABASE_SHARD_URLS = [ + 'https://FOO.firebaseio.com', + 'https://BAR.firebaseio.com', + 'https://BAZ.firebaseio.com', +]; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideDatabase((app: FirebaseApp) => getDatabase(app, DATABASE_SHARD_URLS[0])), + provideDatabase((app: FirebaseApp) => getDatabase(app, DATABASE_SHARD_URLS[1])), + provideDatabase((app: FirebaseApp) => getDatabase(app, DATABASE_SHARD_URLS[2])), + ] +}) +``` + +```ts +import { DatabaseInstances } from '@angular/fire/database'; + +constructor(databases: DatabaseInstances) { + // databases => Database[] +} +``` diff --git a/docs/firestore.md b/docs/firestore.md new file mode 100644 index 000000000..a3c0e02f4 --- /dev/null +++ b/docs/firestore.md @@ -0,0 +1,148 @@ + + + +AngularFireDeveloper Guide ❱ Realtime Cloud Firestore + + +# Cloud Firestore + +Cloud Firestore is a flexible, scalable NoSQL database for mobile, web, and server development from Firebase and Google Cloud. It keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. + +[Learn more](https://firebase.google.com/docs/firestore) + +Cloud Firestore is the API that gives your application access to your database in the cloud or locally in your [emulator](https://firebase.google.com/docs/emulator-suite). + +## Dependency Injection + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` +Provide a Firestore instance in the application's `NgModule` (`app.module.ts`): + +```typescript +@NgModule({ + declarations: [ + ... + ], + imports: [ + ... + // App initialization + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideFirestore(() => getFirestore()) + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } +``` + + +In your component class, for example `user-profile.component.ts` import and inject `Firestore`: + +```typescript +import { Component, inject } from '@angular/core'; +import { Firestore } from '@angular/fire/firestore'; + +@Component({ + standalone: true, + selector: 'app-user-profile', + ... +}) +export class UserProfileComponent { + private firestore: Firestore = inject(Firestore); + ... +} +``` + +## Firebase API +With the reference to Cloud Firestore available in a component it is now possible to connect read from and write to the database. + +### Reading data +In Cloud Firestore data is stored in `documents` and `documents` are stored in `collections`. The path to data follows `/` and continues if there are subcollections. For example, `"users/ABC1245/posts/XYZ6789"` represents: +* `users` collection +* document id `ABC12345` +* `posts` collection +* document id `XYZ6789` + + +Let's explore reading data in Angular using the `collection` and `collectionData` functions. + +In `user-profile.component.ts`: + +```typescript +import { Firestore, collection, collectionData} from '@angular/fire/firestore'; +import { Component, inject } from '@angular/core'; + +@Component ({ + selector: 'app-user-profile', + standalone: true, + ... +}) +export class UserProfileComponent { + private firestore: Firestore = inject(Firestore); // inject Cloud Firestore + users$: Observable; + + constructor() { + // get a reference to the user-profile collection + const userProfileCollection = collection(this.firestore, 'users'); + + // get documents (data) from the collection using collectionData + this.users$ = collectionData(userProfileCollection) as Observable; + } +} +export Interface UserProfile { + username: string; +} +``` +`collectionData` returns an `observable` that can we can use to display the data in the template. In `user-profile.component.html`: + +```html +
+

User Profiles

+
    +
  • + {{user.username}} +
  • +
+
+``` + +The `async` pipe handles unsubscribing from observables. + +### Writing data +To write to Cloud Firestore use the `addDoc` function. It will create a new document at the path specified by the collection. In `user-profile.component.ts`, we'll update the code to add a new document on a ` - - -``` - -and finally, add the corresponding click handlers in `home.ts` as follows. -Also, ensure the *AuthService* is injected in the constructor. Your `home.ts` should look like this - -```ts - -import { Component } from '@angular/core'; -import { NavController } from 'ionic-angular'; - -import { AuthService } from '../../providers/auth-service'; -import { AngularFireDatabase, FirebaseListObservable } from 'AngularFire/database'; - -@Component({ - selector: 'page-home', - templateUrl: 'home.html' -}) -export class HomePage { - - items: FirebaseListObservable; - - constructor(public navCtrl: NavController, db: AngularFireDatabase, private _auth: AuthService) { - this.items = db.list('/items'); - } - - signInWithFacebook(): void { - this._auth.signInWithFacebook() - .then(() => this.onSignInSuccess()); - } - - private onSignInSuccess(): void { - console.log("Facebook display name ",this._auth.displayName()); - } - -} - -``` - -Now run your app and if everything is configured correctly, you should be able to click on the login button in your app, -which should open the facebook pop-up. - -Once you authenticate yourself, you should see your Facebook display name in console. - -You can try redirecting yourself to another page to grab additional details from Facebook. - - -***Running our application on mobile phone.*** - -Ensure you've the platform added to your project. If not add the platform by executing the following command. - -``` - -C:\projects\Ionic_AngularFire_Project>ionic platform add android - -``` - -This adds android platform for your project. -Replace android with ios, if you're on Mac book or add both. The generic command is ```ionic platform add ``` - -Now, let's try to run the app in browser. Execute the command - -``` - -C:\projects\Ionic_AngularFire_Project> ionic run android - -``` - -This should run the app on your mobile phone. Now click on the Facebook button and you'll notice the button doesn't work anymore. -This is because the code written so far is good for running our application in browsers, but when running the application on mobile phones, we need to have access to ***Native Mobile API's***, which are provided by _Cordova Plugins_. - -**We can access these cordova plugins, using Ionic Native, which are nothing but wrappers for cordova plugins.** - -List of all Ionic Native API's for cordova plugins can be found [here](http://ionicframework.com/docs/v2/native/). - -Let's look at configuring and installing facebook plugin [here](http://ionicframework.com/docs/v2/native/facebook/). -_Ensure you follow the steps correctly to configure your app._ - - Once you create your app and make a note of your App ID, go to command prompt in your project directory and execute the following command - - ``` - C:\projects\Ionic_AngularFire_Project> - ionic plugin add cordova-plugin-facebook4 --save --variable APP_ID="123456789" --variable APP_NAME="myApp" - - ``` - -Replace App ID with your app id from portal and provide your app name. - -This will install the cordova plugin for facebook. - -Add the platform to your facebook portal as mentioned in the document [here](http://ionicframework.com/docs/v2/native/facebook/). - -Now import the Platform and Facebook objects in your ```auth-service.ts``` - -```ts -import { Platform } from 'ionic-angular'; -import { Facebook } from 'ionic-native'; -``` - -and update the signInWithFacebook() method. - -your ```auth-service.ts``` code should look like this. - -```ts -import { Observable } from 'rxjs/Observable'; -import { Injectable } from '@angular/core'; -import { AngularFireAuth } from 'AngularFire/auth'; -// Do not import from 'firebase' as you'll lose the tree shaking benefits -import firebase from 'firebase/app'; - -import { Platform } from 'ionic-angular'; -import { Facebook } from 'ionic-native'; - -@Injectable() -export class AuthService { - private currentUser: firebase.User; - - constructor(public afAuth: AngularFireAuth) { - afAuth.authState.subscribe((user: firebase.User) => this.currentUser = user); - } - - get authenticated(): boolean { - return this.currentUser !== null; - } - - signInWithFacebook(): firebase.Promise { - if (this.platform.is('cordova')) { - return Facebook.login(['email', 'public_profile']).then(res => { - const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken); - return this.afAuth.auth.signInWithCredential(facebookCredential); - }); - } else { - return this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()); - } - - } - - signOut(): void { - this.afAuth.auth.signOut(); - } - - displayName(): string { - if (this.currentUser !== null) { - return this.currentUser.facebook.displayName; - } else { - return ''; - } - } -} - - -``` - -Verfiy your app is running in browser by executing the following command - -``` - -C:\projects\Ionic_AngularFire_Project>ionic serve - -``` - -Everything should work. Now trying running the app on your android phone - -``` - -C:\projects\Ionic_AngularFire_Project> ionic run android - -``` - -Once the App launches click on the Facebook login button and it should open up the native facebook app for authentication and once your enter credentials and gets succesfully authenticated, it should redirect you back to the home page. diff --git a/docs/ionic/v3.md b/docs/ionic/v3.md deleted file mode 100644 index 174bf4b47..000000000 --- a/docs/ionic/v3.md +++ /dev/null @@ -1,705 +0,0 @@ -# Using AngularFire with Ionic 3 - -This tutorial provides a walkthrough of integrating AngularFire Authentication with Ionic 3 /Angular 4+. -The below setup has been tested on Windows 10 and macOS Sierra, but it should be same for Linux. - -Note: - If you're working with Ionic2 and Angular2.0, then you should refer to **Auth-with-Ionic2** tutorial -[here](https://github.com/angular/angularfire2/blob/master/docs/Auth-with-Ionic2.md) - -Ensure that you're executing these commands as **Administrator** on Windows and **sudo** on Mac/Linux if you get any permission errors. - -This tutorial uses **Facebook** as the sign-in provider. After completing this tutorial, you should be able to configure -other sign-in providers like **Twitter**, **Google** on your own. - -### Prerequisites -The first step is to ensure you have latest version of **Node** installed. -You can get the latest version from [nodejs.org](https://nodejs.org). -This will install both `node` and `npm`. - -After installing node, check the version by executing the following command in your prompt window: - -```bash - -$ node -v -v6.10.2 -``` - -As of this writing, this is the most stable version. If you're not on this version, -please upgrade yourself to latest stable version by installing node from [nodejs.org](https://nodejs.org). - -Check your npm version by executing the following command: -```bash - -$ npm -v -3.10.10 -``` -Install the Angular CLI, which will be used to build our Angular project and install Angular version 4 or later. - -```bash -$ npm install -g @angular/cli -``` -Check your angular version by executing the following command: - -```bash -$ ng -v - -@angular/cli: 1.0.0 -node: 6.10.2 -os: win32 x64 -``` - -**_Your Application code sits on top of Ionic Framework and the Ionic Framework sits on top of Cordova._** - -Let's get them installed globally, so that all projects can use them. - -Execute the following commands. - -```bash - -$ npm install -g cordova ionic -``` - -Once the above command is executed successfully, check the versions of cordova and ionic: - -```bash -$ cordova -v -7.0.1 - -$ ionic -v -3.4.0 -``` - -You're all set to create your app with Ionic framework. - -To create your app, change into the directory where you want your app to reside and execute the following command: - -```bash -$ ionic start auth-ng4-ionic3-af2 blank -``` - ->The command ionic start will create the project with name "auth-ng4-ionic3-af2" using "blank" template. - -Change to the project directory, which was just created with the above command. - -``` -$ ionic info - -global packages: - - @ionic/cli-utils : 1.4.0 - Cordova CLI : 7.0.1 - Ionic CLI : 3.4.0 - -local packages: - - @ionic/app-scripts : 1.3.12 - @ionic/cli-plugin-cordova : 1.4.0 - @ionic/cli-plugin-ionic-angular : 1.3.1 - Cordova Platforms : none - Ionic Framework : ionic-angular 3.5.0 - -System: - - Node : v8.1.2 - OS : Windows 10 - Xcode : not installed - ios-deploy : not installed - ios-sim : not installed - npm : 5.0.4 -``` -You need to ensure you've got Ionic Framework Version 3, as shown above. - -Alternatively you can open `package.json` to ensure you've got the following Angular and Ionic versions: - -```json -"dependencies": { - "@angular/common": "4.1.3", - "@angular/compiler": "4.1.3", - "@angular/compiler-cli": "4.1.3", - "@angular/core": "4.1.3", - "@angular/forms": "4.1.3", - "@angular/http": "4.1.3", - "@angular/platform-browser": "4.1.3", - "@angular/platform-browser-dynamic": "4.1.3", - "@ionic-native/core": "3.12.1", - "@ionic-native/splash-screen": "3.12.1", - "@ionic-native/status-bar": "3.12.1", - "@ionic/storage": "2.0.1", - "ionic-angular": "3.6.0", - "ionicons": "3.0.0", - "rxjs": "5.4.0", - "sw-toolbox": "3.6.0", - "zone.js": "0.8.12" - }, - "devDependencies": { - "@ionic/app-scripts": "1.3.12", - "@ionic/cli-plugin-ionic-angular": "1.3.1", - "typescript": "~2.3.4" - } - -``` - -If not, replace them to match above. These are the latest as of writing this tutorial. - -To start your app, execute the following command: - -```bash - -$ ionic serve -``` -If everything is installed correctly, the app should open your browser with the dev server running at the following url -**`http://localhost:8100`** and will display default home page. - -### Configuring AngularFire and Firebase - -Install the required packages in your project directory: - -```ts - -$ npm install angularfire2 firebase promise-polyfill --save - -``` - -_This should add angularfire2, promise-polyfill and firebase entry in your project's package.json file as dependencies. Something similar to:_ - -``` -"angularfire2": "^4.0.0-rc.1", -"firebase": "^4.1.3", -"promise-polyfill": "^6.0.2", -``` - -As the Angularfire2 v5+ rc10 requires rxjs6, you need to install rxjs-compat for angular version < 6.0: -``` -npm install rxjs@6 rxjs-compat@6 promise-polyfill --save -``` -### Setup @NgModule - -Open your project in your favourite editor and open the `app.module.ts` file, under `src/app` -and add the following three entries. - -1) Import AngularFireModule and AngularFireDatabaseModule at top. - -2) Define your firebaseConfig constant. - -3) Initialize your app, by adding AngularFireModule and AngularFireAuthModule in the "imports" array in @NgModule - -4) Also, add AngularFireDatabase in the "providers" array in @NgModule - -your `app.module.ts` file should look something like this. - -```typescript - -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'; - -import { AngularFireModule } from '@angular/fire/compat'; -import { AngularFireDatabaseModule, AngularFireDatabase } from '@angular/fire/compat/database'; -import { AngularFireAuthModule } from '@angular/fire/compat/auth'; - -export const firebaseConfig = { - apiKey: "xxxxxxxxxx", - authDomain: "your-domain-name.firebaseapp.com", - databaseURL: "https://your-domain-name.firebaseio.com", - storageBucket: "your-domain-name.appspot.com", - messagingSenderId: '' -}; - -@NgModule({ - declarations: [ - MyApp, - HomePage - ], - imports: [ - BrowserModule, - IonicModule.forRoot(MyApp), - AngularFireModule.initializeApp(firebaseConfig), - AngularFireDatabaseModule, - AngularFireAuthModule - ], - bootstrap: [IonicApp], - entryComponents: [ - MyApp, - HomePage - ], - providers: [ - StatusBar, - SplashScreen, - AngularFireDatabase, - {provide: ErrorHandler, useClass: IonicErrorHandler} - ] -}) -export class AppModule {} - -``` - -### Inject AngularFire and Bind it to List - -Now inject AngularFireDatabase in your component. Open your `home.ts` by going into `src/pages/home/home.ts` and make the -following changes: - ->1) Import "AngularFireDatabase" at the top of your component. - ->2) Inject your AngularFireDatabase dependency in the constructor. - ->3) Call the list method on AngularFireDatabase object. - -Your `home.ts` file should look like this: - -```typescript - -import { Component } from '@angular/core'; -import { NavController } from 'ionic-angular'; - -import { AngularFireDatabase } from '@angular/fire/compat/database'; -import { Observable } from 'rxjs/Observable'; - -@Component({ - selector: 'page-home', - templateUrl: 'home.html' -}) -export class HomePage { - items: Observable; - - constructor(public navCtrl: NavController, afDB: AngularFireDatabase) { - this.items = afDB.list('cuisines').valueChanges(); - } - -} - -``` - -*_Ensure you've `cuisines` node in your database with some primitive data._ - -**Update** your `home.html` at `src/pages/home/home.html`, with following entry - -```html - - - - - Ionic Blank - - - - - - - - {{item | json}} - - - - -``` - -**Run your app by executing the following command** - -```bash - -C:\projects\auth-ng4-ionic3-af2> ionic serve - -``` - -This should fetch the data from firebase. - - -## Configuring Firebase/Facebook to talk to each other - -Go to Facebook Developers Page [here](https://developers.facebook.com/apps/) and create a new App. - -Once the App is created, get the `App ID` and `App Secret` from the dashboard and come back to _*Firebase Console*_. - -1) Login to Firebase Console and click on the Authentication section on the left hand side of the menu. -2) Click on Sign-In Method tab and click on Facebook under Sign-In Providers. -3) Paste the `App ID` and `App Secret` copied from Facebook dashboard here. -4) Next copy the "OAuth redirect URI" from Firebase console. We need to go back and add it in Facebook dashboard. - -_This URI is important, since it tells facebook, where to redirect a user, once he is successfully authenticated._ - -5) Click the Save button and come back to the facebook dashboard. - -Go to your app in Facebook developers site ( Facebook Dashboard ) - -6) Ensure you see `Facebook Login` under products section, if not add it via the Add Product Button. -7) Once you see Facebook Login under products, click on the button to go to settings and there you should -see "Valid OAuth redirect URIs" input field. -8) Enter the URI copied from Firebase Console and click on Save Changes. - -*_That's it. This will ensure Facebook and Firebase are able to talk to each other._* - -`As we were able to fetch data from Firebase database in the above step, let's focus on authentication below, by -removing calls to fetch data.` - -*Let's add the following two buttons in our `home.html`* - -The `home.html` should look like below - -```html - - - - - Auth with Ionic - - - - - - - - - -``` - -Let's update the `home.ts` to add the corresponding methods: - -1) First import AngularFireAuth from `angularfire2/auth`. -2) Inject AngularFireAuth in the constructor -3) The AngularFireAuth has various signIn methods to which we can pass instance of AuthProviders as shown below. - -The `home.ts` should look like below - -```typescript -import { Component } from '@angular/core'; -import { NavController } from 'ionic-angular'; - -import { AngularFireAuth } from '@angular/fire/compat/auth'; -import firebase from 'firebase/app'; - -@Component({ - selector: 'page-home', - templateUrl: 'home.html' -}) -export class HomePage { - - constructor(public navCtrl: NavController, - private afAuth: AngularFireAuth) { } - - signInWithFacebook() { - this.afAuth.auth - .signInWithPopup(new firebase.auth.FacebookAuthProvider()) - .then(res => console.log(res)); - } - - signOut() { - this.afAuth.auth.signOut(); - } - -} - -``` -**_Note the import of firebase from firebase/app, to take advantage of the tree-shaking_** - -Also, update your `app.module.ts` to contain following import - -`import { AngularFireAuthModule } from '@angular/fire/compat/auth';` - -and add it to the imports array. - - -Run the app and click on the Login Button, you should see a pop-up asking you to enter username and password for Facebook to -authenticate. Once authenticated, you should see the response from Facebook in console window. - -Inspect the Object in the console, under `user` property, you should see all the attributes and we're going to use two of them, next. - -Let's get the `displayName` from the `user` property, which we just saw on the console to be rendered on the screen. -The `AngularFireAuth` has an `authState` property, which returns an observable, let's subcribe it to get notified everytime the -Authentication state changes. - -Add class property `displayName` and subscribe to the AngularFireAuth.authState property in the constructor. -Also add the property in our template to render them on screen. - -Your `home.ts` should look as follows: - -```typescript - -import { Component } from '@angular/core'; -import { NavController } from 'ionic-angular'; - -import { AngularFireAuth } from '@angular/fire/compat/auth'; -import firebase from 'firebase/app'; - -@Component({ - selector: 'page-home', - templateUrl: 'home.html' -}) -export class HomePage { - - displayName; - - constructor(public navCtrl: NavController, - private afAuth: AngularFireAuth) { - afAuth.authState.subscribe(user => { - if (!user) { - this.displayName = null; - return; - } - this.displayName = user.displayName; - }); - } - - signInWithFacebook() { - this.afAuth.auth - .signInWithPopup(new firebase.auth.FacebookAuthProvider()) - .then(res => console.log(res)); - } - - signOut() { - this.afAuth.auth.signOut(); - } - -} - - -``` - -and `home.html` should look like this: - -```html - - - - - Auth with Ionic - - - - - - -

Hello {{displayName}}

- - - -
- -``` - -Now run your app and if everything is configured correctly, you should be able to click on the login button in your app, -which should open the facebook pop-up. - -Once you authenticate yourself, you should see your Facebook display name on your screen. -Click the Logout button, which will make the AuthState to null and you should see the difference on your screen. - -You can try redirecting yourself to another page to grab additional details from Facebook and experiment on your own. - - -***Running our application on mobile phone*** - -Ensure you've the platform added to your project. If not add the platform by executing the following command: - -``` - -C:\projects\auth-ng4-ionic3-af2>ionic platform add android - -``` - -This adds android platform for your project. -Replace android with ios, if you're on Mac book or add both. The generic command is ```ionic platform add ``` - -Now, let's try to run the app in browser. Execute the command: - -``` - -C:\projects\auth-ng4-ionic3-af2> ionic run android - -``` - -This should run the app on your mobile phone. Now click on the Facebook button and you'll notice the button doesn't work anymore. -This is because the code written so far is good for running our application in browsers, but when running the application on -mobile phones, we need to have access to ***Native Mobile API's***, which are provided by _Cordova Plugins_. - -**We can access these cordova plugins, using Ionic Native, which are nothing but wrappers for cordova plugins.** - -List of all Ionic Native API's for cordova plugins can be found [here](http://ionicframework.com/docs/v2/native/). - -Let's look at configuring and installing the Facebook plugin [here](http://ionicframework.com/docs/v2/native/facebook/). -_Ensure you follow the steps correctly to configure your app._ - -Login to the Facebook dashboard [here](https://developers.facebook.com/apps/), go to your App and make a note of your App ID. -Next go to command prompt in your project directory and execute the following command by replacing the `APP_ID` with your App Id -and `APP_NAME` with your App Name. - - ```bash - -C:\projects\auth-ng4-ionic3-af2> -ionic cordova plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication" - -``` - -This should add the following entry in your config.xml, located at the root of your project: - -```xml - - - - - - -``` -This will install the cordova plugin for facebook. - -You should also see a sub-folder named `cordova-plugin-facebook4` under your `plugins` folder. - -Add the native dependencies by executing the following command: - -```bash - -C:\projects\auth-ng4-ionic3-af2>npm install --save @ionic-native/facebook - -``` - -After executing the above command, ensure you have the following entry in your `package.json`: - -```bash - -"@ionic-native/facebook": "^3.12.1", - -``` -Now import the `Platform` and `Facebook` objects in your `home.ts` and inject the objects in constructor. - -```typescript - -import { Platform } from 'ionic-angular'; -import { Facebook } from '@ionic-native/facebook'; - -``` - -Update the "signInWithFacebook" method and use Platform Service to determine the platform and run the appropriate code. - -Your `home.ts` should look as below: - -```typescript - -import { Component } from '@angular/core'; -import { NavController } from 'ionic-angular'; - -import { AngularFireAuth } from '@angular/fire/compat/auth'; -import firebase from 'firebase/app'; - -import { Platform } from 'ionic-angular'; -import { Facebook } from '@ionic-native/facebook'; - -@Component({ - selector: 'page-home', - templateUrl: 'home.html' -}) -export class HomePage { - - displayName; - - constructor(public navCtrl: NavController, - private afAuth: AngularFireAuth, private fb: Facebook, private platform: Platform) { - afAuth.authState.subscribe((user: firebase.User) => { - if (!user) { - this.displayName = null; - return; - } - this.displayName = user.displayName; - }); - } - - signInWithFacebook() { - if (this.platform.is('cordova')) { - return this.fb.login(['email', 'public_profile']).then(res => { - const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken); - return firebase.auth().signInWithCredential(facebookCredential); - }) - } - else { - return this.afAuth.auth - .signInWithPopup(new firebase.auth.FacebookAuthProvider()) - .then(res => console.log(res)); - } - } - - signOut() { - this.afAuth.auth.signOut(); - } - -} - - -``` - -You'll also need to add the "Facebook" object in the provider section in app.module.ts. - -The final `app.module.ts` should look like below: - -```typescript - -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'; - -import { AngularFireModule } from '@angular/fire/compat'; -import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; -import { AngularFireAuthModule } from '@angular/fire/compat/auth'; -import { Facebook } from '@ionic-native/facebook'; - -export const firebaseConfig = { - apiKey: "xxxxxxxxxx", - authDomain: "your-domain-name.firebaseapp.com", - databaseURL: "https://your-domain-name.firebaseio.com", - storageBucket: "your-domain-name.appspot.com", - messagingSenderId: '' -}; - -@NgModule({ - declarations: [ - MyApp, - HomePage - ], - imports: [ - BrowserModule, - IonicModule.forRoot(MyApp), - AngularFireModule.initializeApp(firebaseConfig), - AngularFireDatabaseModule, - AngularFireAuthModule - ], - bootstrap: [IonicApp], - entryComponents: [ - MyApp, - HomePage - ], - providers: [ - StatusBar, - SplashScreen, - {provide: ErrorHandler, useClass: IonicErrorHandler}, - Facebook - ] -}) -export class AppModule {} - - -``` - -Verfiy your app is running in browser by executing the following command: - -```bash - -C:\projects\auth-ng4-ionic3-af2>ionic serve - -``` - -Everything should work. Now trying running the app on your android phone: - -```bash - -C:\projects\auth-ng4-ionic3-af2> ionic cordova run android - -``` - -Once the App launches click on the Login button. You should get the Facebook pop-up window. Enter your credentials. -On successful authentication, you should see your Facebook Display name and profile picture on your screen. diff --git a/docs/messaging.md b/docs/messaging.md new file mode 100644 index 000000000..a1203c55a --- /dev/null +++ b/docs/messaging.md @@ -0,0 +1,25 @@ + + + +AngularFireDeveloper Guide ❱ Realtime Cloud Messaging + + +# Cloud Messaging + +The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API. + +[Learn More](https://firebase.google.com/docs/cloud-messaging/) + +## Dependency Injection + +YADA YADA YADA + +## Firebase API + +Something something look at the offical docs + +## Convenience observables + +### Foo + +bar baz \ No newline at end of file diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 000000000..3705b3e8f --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,57 @@ + + + +AngularFireDeveloper Guide ❱ Realtime Performance Monitoring + + +# Performance Monitoring + +Firebase Performance Monitoring is a service that helps you to gain insight into the performance characteristics of your Apple, Android, and web apps. + +[Learn More](https://firebase.google.com/docs/perf-mon) + +## Dependency Injection + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide a Performance instance and configuration in the application's `NgModule` (`app.module.ts`): + +```ts +import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; +import { getPerformance, providePerformance} from '@angular/fire/performance'; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + providePerformance(() => getPerformance()), + ] +}) +``` + +Next inject it into your component: + +```ts +import { Component, inject} from '@angular/core'; +import { Performance } from '@angular/fire/performance'; + +@Component({ ... }) +export class PerformanceComponent { + private performance: Performance = inject(Performance); + ... +} +``` + +## Firebase API + +The [Performance documentation](https://firebase.google.com/docs/reference/js/performance.md#performance_package) is available on the Firebase website. + +## Services + +Coming soon. + +## Convenience observables + +Coming soon. \ No newline at end of file diff --git a/docs/remote-config.md b/docs/remote-config.md new file mode 100644 index 000000000..df2955e73 --- /dev/null +++ b/docs/remote-config.md @@ -0,0 +1,53 @@ + + + +AngularFireDeveloper Guide ❱ Realtime Remote Config + + +# Remote Config + +Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update. + +[Learn More](https://firebase.google.com/docs/remote-config/) + +## Dependency Injection + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide a Performance instance and configuration in the application's `NgModule` (`app.module.ts`): + +```ts +import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; +import { getRemoteConfig, provideRemoteConfig} from '@angular/fire/remote-config'; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideRemoteConfig(() => getRemoteConfig()), + ] +}) +``` + +Next inject it into your component: + +```ts +import { Component, inject} from '@angular/core'; +import { RemoteConfig } from '@angular/fire/remote-config'; + +@Component({ ... }) +export class RemoteConfigComponent { + private remoteConfig: RemoteConfig = inject(RemoteConfig); + ... +} +``` + +## Firebase API + +The [Remote Config documentation](https://firebase.google.com/docs/reference/js/remote-config) is available on the Firebase website. + +## Convenience observables + +Coming soon. \ No newline at end of file diff --git a/docs/storage.md b/docs/storage.md new file mode 100644 index 000000000..3a54f2003 --- /dev/null +++ b/docs/storage.md @@ -0,0 +1,90 @@ + + + +AngularFireDeveloper Guide ❱ Realtime Cloud Storage + + +# Cloud Storage + +Cloud Storage allows developers to upload and share user generated content such as images, video and more. Data is stored in Google Cloud Storage. + +[Learn more](https://firebase.google.com/docs/storage) + +## Dependency Injection + +AngularFire allows you to work with Firebase Storage via Angular's Dependency Injection. + +As a prerequisite, ensure that `AngularFire` has been added to your project via +```bash +ng add @angular/fire +``` + +Provide a Firebase Storage instance in the application's `NgModule` (`app.module.ts`): + +```ts +import { provideFirebaseApp, initializeApp } from '@angular/fire/app'; +import { getStorage, provideStorage } from '@angular/fire/storage'; + +@NgModule({ + imports: [ + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideStorage(() => getStorage()), + ] +}) +``` + +Next inject it into your component: + +```ts +import { Component, inject} from '@angular/core'; +import { Storage } from '@angular/fire/storage'; + +@Component({ ... }) +export class StorageComponent { + private storage: Storage = inject(Storage); + ... +} +``` + + +## Firebase API + +AngularFire wraps the Firebase JS SDK to ensure proper functionality in Angular, while providing the same API. + +Update the imports from `import { ... } from 'firebase/storage'` to `import { ... } from '@angular/fire/storage'` and follow the offical documentation. + +[Getting Started](https://firebase.google.com/docs/storage/web/start) | [API Reference](https://firebase.google.com/docs/reference/js/storage) + +## File Upload Example + +```ts +import { Component, inject } from '@angular/core'; +import { Storage, ref, uploadBytesResumable } from '@angular/fire/storage'; + +@Component({ + selector: 'app-storage', + template: ` +

Storage

+ + + + `, +}) +export class StorageComponent { + private readonly storage: Storage = inject(Storage); + + uploadFile(input: HTMLInputElement) { + if (!input.files) return + + const files: FileList = input.files; + + for (let i = 0; i < files.length; i++) { + const file = files.item(i); + if (file) { + const storageRef = ref(this.storage, file.name); + uploadBytesResumable(storageRef, file); + } + } + } +} +``` \ No newline at end of file diff --git a/site/src/get-started/quick-start.md b/site/src/get-started/quick-start.md index a4f91d1ff..0258bf28a 100644 --- a/site/src/get-started/quick-start.md +++ b/site/src/get-started/quick-start.md @@ -25,7 +25,7 @@ Now that you have a new project setup, install AngularFire and Firebase from npm ## Add Firebase config to environments variable -Open `/src/environments/environment.ts` and add your Firebase configuration. You can find your project configuration in [the Firebase Console](https://console.firebase.google.com). Click the Gear icon next to Project Overview, in the Your Apps section, create a new app and choose the type Web. Give the app a name and copy the config values provided. +Open `/src/environments/environment.ts`, create it if it doesn't exist, and add your Firebase configuration. You can find your project configuration in [the Firebase Console](https://console.firebase.google.com). Click the Gear icon next to Project Overview, in the Your Apps section, create a new app and choose the type Web. Give the app a name and copy the config values provided. ```ts export const environment = { @@ -43,47 +43,78 @@ export const environment = { }; ``` -## Setup `@NgModule` for the `AngularFireModule` +## Configuring Firebase in your Angular Application -Open `/src/app/app.module.ts`, inject the Firebase providers, and specify your Firebase configuration. +### Set up Firebase for `@NgModule` based apps +For applications bootstrapped using `@NgModule`, add the Firebase providers to the imports array of the `@NgModule` decorator metadata. + +In `/src/app/app.module.ts` update the code to:. ```ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; -import { AngularFireModule } from '@angular/fire'; +import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, - AngularFireModule.initializeApp(environment.firebase) + provideFirebaseApp(() => initializeApp(environment.firebase)), ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {} ``` +### Set up Firebase for Standalone API based apps +Beginning in [Angular v14](https://blog.angular.io/angular-v14-is-now-available-391a6db736af) applications can be built and bootstrapped using the set of [Standalone APIs](https://angular.io/guide/standalone-components). + +The provider configuration for these applications should be added to the `bootstrapApplication` function in `main.ts`: + +```ts +import { importProvidersFrom } from '@angular/core'; +import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; +import { getAuth, provideAuth } from '@angular/fire/auth'; +import { bootstrapApplication } from '@angular/platform-browser'; +import { AppComponent } from './app/app.component'; +import { environment } from './environments/environment'; + + +bootstrapApplication(AppComponent, { + providers: [ + importProvidersFrom( + provideFirebaseApp(()=> initializeApp(environment.firebase)) + ), + ], +}).catch(err => console.error(err)); +``` -## Setup individual `@NgModule`s +Note that you are required to wrap the `provideFirebaseApp` function call in the `importProvidersFrom` function. -After adding the AngularFireModule you also need to add modules for the individual @NgModules that your application needs. +### Configuring Firebase features -For example if your application was using both Google Analytics and the Firestore you would add `AngularFireAnalyticsModule` and `AngularFirestoreModule`: +After adding the Firbase app providers, you also need to add providers for the each of Firebase features your application needs. + +For example if your application uses both Google Analytics and the Firestore database you would add `provideAnalytics` and `provideFirestore`: ```ts +// Module based configuration app.module.ts + import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; -import { AngularFireModule } from '@angular/fire'; -import { AngularFireAnalyticsModule } from '@angular/fire/analytics'; -import { AngularFirestoreModule } from '@angular/fire/firestore'; +import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; +import { provideAnalytics, getAnalytics } from '@angular/fire/analytics'; +import { provideFirestore, getFirestore } from '@angular/fire/firestore'; import { environment } from '../environments/environment'; @NgModule({ imports: [ BrowserModule, - AngularFireModule.initializeApp(environment.firebase), + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideAnalytics(()=> getAnalytics()), + provideFirestore(() => getFirestore()), AngularFireAnalyticsModule, AngularFirestoreModule ], @@ -93,13 +124,34 @@ import { environment } from '../environments/environment'; export class AppModule {} ``` +```ts +// Standalone API based config (main.ts) +import { importProvidersFrom } from '@angular/core'; +import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; +import { provideFirestore, getFirestore } from '@angular/fire/firestore' +import { getAuth, provideAuth } from '@angular/fire/auth'; +import { bootstrapApplication } from '@angular/platform-browser'; +import { AppComponent } from './app/app.component'; +import { environment } from './environments/environment'; + + +bootstrapApplication(AppComponent, { + providers: [ + importProvidersFrom( + provideFirebaseApp(() => initializeApp(environment.firebase)), + provideAuth(() => getAuth()), + provideFirestore(() => getFirestore()) + ), + ], +}).catch(err => console.error(err)); +``` ## Inject `AngularFirestore` Open `/src/app/app.component.ts`, and make sure to modify/delete any tests to get the sample working (tests are still important, you know): ```ts -import { Component } from '@angular/core'; -import { AngularFirestore } from '@angular/fire/firestore'; +import { Component, inject } from '@angular/core'; +import { Firestore } from '@angular/fire/firestore'; @Component({ selector: 'app-root', @@ -107,9 +159,8 @@ import { AngularFirestore } from '@angular/fire/firestore'; styleUrls: ['app.component.css'] }) export class AppComponent { - constructor(firestore: AngularFirestore) { - - } + private firestore: AngularFirestore = inject(Firestore) + ... } ``` @@ -119,7 +170,7 @@ In `/src/app/app.component.ts`: ```ts import { Component } from '@angular/core'; -import { AngularFirestore } from '@angular/fire/firestore'; +import { Firestore, collection } from '@angular/fire/firestore'; import { Observable } from 'rxjs'; @Component({ @@ -128,9 +179,12 @@ import { Observable } from 'rxjs'; styleUrls: ['app.component.css'] }) export class AppComponent { - items: Observable; - constructor(firestore: AngularFirestore) { - this.items = firestore.collection('items').valueChanges(); + private firestore: Firestore = inject(Firestore); + items$: Observable; + + constructor() { + const itemsCollectionRef = collection(this.firestore, 'items'); + this.items = collectionData(itemsCollectionRef) as Observable; } } ``` @@ -139,7 +193,7 @@ Open `/src/app/app.component.html`: ```html
    -
  • +
  • {{item.name}}