firebase auth_如何使用auth和实时数据库构建Firebase Angular应用

卫飞鹏
2023-12-01

firebase auth

by Zdravko Kolev

通过Zdravko Kolev

如何使用auth和实时数据库构建Firebase Angular应用 (How to build a Firebase Angular app with auth and a real-time database)

For a long time, I was looking for a good Portfolio web app that can help me to easily track my Cryptocurrency profits/losses until I’ve decided to develop such on my own with the help of Firebase and Angular! Yes, it’s that easy, let me explain to you why.

长期以来,我一直在寻找一个好的Portfolio Web应用程序,该应用程序可以帮助我轻松跟踪我的加密货币盈亏,直到我决定借助Firebase和Angular自行开发此类资产! 是的,就是这么简单,让我向您解释原因。

Firebase gives the perfect tooling for applications with user authentication and Real-time database storage needs. It provides rich documentation with a variety of dev examples to help anyone gain a better understanding of how to create stellar apps.

Firebase为具有用户身份验证和实时数据库存储需求的应用程序提供了完美的工具。 它提供了丰富的文档以及各种开发示例,以帮助任何人更好地了解如何创建出色的应用程序。

I have covered the Angular application bootstrapping, using Ignite UI CLI, in another blog post.

我已经在另一篇博客文章中介绍了使用Ignite UI CLI引导Angular应用程序。

This article aims to:

本文旨在:

配置Firebase帐户 (Configure a Firebase account)

I want to go through the steps that we’ve taken to set up the Portfolio Firebase account. Projects are created from the Firebase console by choosing Add a new project. Once the Create project form is submitted you will see the following Project Overview.

我想完成设置投资组合Firebase帐户所采取的步骤。 通过选择添加新项目Firebase控制台创建项目。 提交创建项目表单后,您将看到以下项目概述。

Under the Project Overview section, you can find all development tools that are used for Authentication and Data storing. Here is also located the configuration which is used in the Portfolio Web App. This configuration is generated by pressing Add Firebase to your web app, and it is later added in application’s app.module.ts file.

在“项目概述”部分下,您可以找到用于身份验证和数据存储的所有开发工具。 还可以找到投资组合Web应用程序中使用的配置。 通过将Add Firebase添加到您的Web应用程序来生成此配置,然后将其添加到应用程序的app.module.ts文件中。

Let’s get back to the sidebar on the left and select Authentication. From here we have access to the Sign-in methods that we need in the app. Navigate to the Sign-in tab, there you can see the providers that are enabled and used in the Portfolio application — Google, Facebook and Email/Password provider.

让我们回到左侧的边栏中,然后选择身份验证 。 从这里,我们可以访问应用程序中所需的登录方法 。 导航到“登录”选项卡,您可以在“投资组合”应用程序中看到已启用和使用的提供商-Google ,Facebook和电子邮件/密码提供商

Sign-in providers let users authenticate with Firebase using their Facebook and Google accounts by integrating their logins into the app. As for the Email/password provider, it represents a simple authentication mechanism by using only email and password. Firebase Auth provides built-in validation rules verifying the user entries, so we don’t need to configure something additional here.

登录提供商可以将用户的登录信息集成到应用中,从而使用户可以使用其Facebook和Google帐户向Firebase进行身份验证。 对于电子邮件/密码提供程序,它仅使用电子邮件和密码表示一种简单的身份验证机制。 Firebase Auth提供了内置的验证规则来验证用户条目,因此我们无需在此处进行其他配置。

The “trickiest” part here was the Facebook provider configuration because we needed to have a Facebook application in order to authenticate the login. We’ve created a FB app from Facebook Developers which provided us with the App ID and App Secret requested from Firebase.

这里最“棘手”的部分是Facebook提供程序配置,因为我们需要一个Facebook应用程序才能对登录进行身份验证。 我们已经从Facebook Developers创建了FB应用,该应用为我们提供了Firebase要求的App ID和App Secret。

Both API ID and Secret should be filled when enabling the Facebook provider. As for the Auth redirect URI (from the provider window) it should be pasted under Facebook/Facebook Login/Products section/Valid Auth Redirect URIs.

启用Facebook提供程序时, API IDSecret均应填写。 至于Auth重定向URI (从提供者窗口),应将其粘贴在Facebook/Facebook Login/Products section/Valid Auth Redirect URIs

Let’s continue with the Firebase console. From the Database view page, we’ve created a Real-time Database.

让我们继续使用Firebase控制台。 从数据库视图页面,我们创建了一个实时数据库。

In this view, we can find information about the application data items and write/read security rules. Below are the rules used by the Portfolio application:

在此视图中,我们可以找到有关应用程序数据项和写入/读取安全规则的信息。 以下是投资组合应用程序使用的规则:

{  "rules": {    "items": {      "$uid": {        ".read": "$uid === auth.uid",        ".write": "$uid === auth.uid"      }    }  }}

This Security Rule configuration will allow only authenticated users to be able to read and write in our database. If you want to learn how to define more advanced rules, I strongly recommend checking out the Official Security & Rules section.

此安全规则配置将仅允许经过身份验证的用户读取和写入我们的数据库。 如果您想学习如何定义更高级的规则,强烈建议您查看“ 官方安全和规则”部分。

Okay, where were we? Now that we’ve gone through the Portfolio Firebase account creation, let’s see how the Firebase development project was created.

好吧,我们在哪里? 现在,我们已经完成了投资组合 Firebase帐户的创建,让我们看看Firebase开发项目是如何创建的。

If we didn’t have a project created already, I would have recommended starting with installing the firebase CLI, that provides a variety of tools for managing and deploying Firebase projects. BUT we’ve bootstrapped the Portfolio Angular Project with Ignite UI CLI, so we just needed to install AngularFire and Firebase from npm. We need both packages in order to communicate with Firebase. AngularFire is the official library for Firebase and Angular development.

如果我们还没有创建项目,那么我建议您从安装firebase CLI开始 ,它提供了多种工具来管理和部署Firebase项目。 但是,我们已经使用Ignite UI CLI引导了Portfolio Angular项目 ,因此我们只需要从npm安装AngularFireFirebase 。 我们需要两个软件包才能与Firebase进行通信。 AngularFire是Firebase和Angular开发的官方库。

npm install firebase @angular/fire --save

All AngularFire modules that are used in the application are added in the app.module.ts file:

应用程序中使用的所有AngularFire模块都添加到app.module.ts文件中:

  • FirestoreModule is needed for the database features like working with collections, queries, and services for data streaming and manipulation.

    数据库功能(例如与集合,查询和数据流和处理服务一起使用)需要FirestoreModule

  • FireAuthModule is needed for authentication features like monitoring authentication state, Log-in providers and security.

    FireAuthModule 监视身份验证状态,登录提供程序和安全性等身份验证功能所需的。

  • FireDatabaseModule allows us to work with Realtime databases. It’s very efficient for mobile and web apps that require synced states across clients in Realtime.

    FireDatabaseModule允许我们使用实时数据库。 对于需要实时在客户端之间同步状态的移动和Web应用程序,它非常高效。

The only common module that is not used in the Portfolio app is AngularFireStorageModule. You can use this module to quickly and easily store and serve user-generated content like photos and videos as well as monitor uploads and metadata associated with files.

组合应用程序中未使用的唯一通用模块是AngularFireStorageModule。 您可以使用此模块快速,轻松地存储和提供用户生成的内容(例如照片和视频),并监视与文件关联的上载和元数据。

Now that we know how the app was configured initially, we can take a look at the other Firebase features that are used.

现在我们知道了应用程序的最初配置方式,接下来我们可以看看所使用的其他Firebase功能

认证方式 (Authentication)

We use AngularFireAuth service to monitor the app authentication state. AngularFireAuth.auth returns an initialized firebase.auth.Auth instance, allowing us to log users in and out. The app demonstrates Sign-in capabilities using three providers: Facebook, Google, and Email.

我们用 AngularFireAuth服务 监视应用程序身份验证状态。 AngularFireAuth.auth返回一个初始化firebase.auth.Auth实例,让我们的用户登录和退出。 该应用程序使用三种提供程序来演示登录功能:Facebook,Google和电子邮件。

Firebase user instance is kept for every provider linked to the user, and when a user is registered or signs in, that user becomes the current user of the Auth instance. The instance persists the user’s state so that refreshing the page or restarting the application doesn’t lose the user’s information.

将为每个与该用户链接的提供程序保留Firebase用户实例,并且当用户注册或登录时,该用户将成为Auth实例的当前用户。 该实例将保持用户的状态,因此刷新页面或重新启动应用程序不会丢失用户的信息。

We use signInWithRedirect method for both Facebook and Google providers, in order to sign in by redirecting to the sign-in page. Password-based account creation is used for the Email sign-in provider, createUserWithEmailAndPassword and signInWithEmailAndPassword are the methods responsible for the user account creation and sign-in.

我们对Facebook和Google提供程序都使用signInWithRedirect方法,以便通过重定向到登录页面进行登录。 基于密码的帐户创建用于电子邮件登录提供程序createUserWithEmailAndPassword signInWithEmailAndPassword 是负责创建和登录用户帐户的方法。

I recommend the official Firebase docs for more detailed information on authentication and user lifecycle.

我建议使用Firebase官方文档,以获取有关身份验证用户生命周期的更多详细信息。

实时数据库操作 (Real-time Database Actions)

Firebase offers two cloud-based, client-accessible database solutions, and we are using Firebase’s original database — Realtime. Check out the differences between Realtime and Cloud firestore on the official documentation page.

Firebase提供了两个基于云的,客户端可访问的数据库解决方案,并且我们正在使用Firebase的原始数据库-Realtime。 在官方文档页面上查看RealtimeCloud firestore之间的区别。

AngularFireDatabase and AngularFireList services are used in the Portfolio app to retrieve, save and remove data easily.

AngularFireDatabase AngularFireList 组合应用程序中使用服务来轻松检索,保存和删除数据。

AngularFireDatabase can be injected through the constructor of a component or @Injectable() service. In our case we use the second approach:

AngularFireDatabase 可以通过组件的构造函数或@Injectable()注入 服务。 在我们的例子中,我们使用第二种方法

Data is retrieved through the AngularFireDatabase service, which fills Observable list of BlockItems. AngularFire provides methods like snapshotChanges() that returns Observable of data as a synchronized array. It is very handy if you want to limit event actions, like added, changed, removed and moved. By default, it listens to all four, however, you may only be interested in one of these events and you can specify which of them you’d like to use. In our application, we are subscribed to all of them.

通过AngularFireDatabase检索数据 服务,该服务填充BlockItems Observable列表。 AngularFire 提供诸如snapshotChanges()类的方法,这些方法以同步数组的形式返回Observable数据。 如果要限制事件动作(例如添加更改删除移动) ,这非常方便。 默认情况下,它会监听全部四个事件,但是,您可能只对其中一个事件感兴趣,并且可以指定要使用的事件。 在我们的应用程序中,我们已订阅所有这些。

Adding a new item, updating an existing one, or removing it from the list is achieved by using push(), update() and remove() methods.

通过使用push()update()remove()方法,可以添加新项目,更新现有项目或将其从列表中remove()

Each data operation method returns a promise, although we don’t need to use the completion promise to indicate success because the real-time database keeps the list in sync.

每个数据操作方法都返回一个Promise,尽管我们不需要使用完成Promise来表示成功,因为实时数据库使列表保持同步。

可观察的 (Observables)

CoinItem服务 (CoinItem service)

Cryptocompare API service manages async data and emits multiple values at a time with Observables. We use HttpClient get()method to request the data from the resource and subscribe to it, in order to transform it to Observable Array of CoinItem objects, which will be used later by our igxGrid, igxList, and igxCard components.

Cryptocompare API服务使用Observables管理异步数据并一次发出多个值。 我们使用HttpClient get( )方法从资源中请求数据并进行订阅,以便将其转换为CoinItem Observable Array 对象,稍后将由我们的igxGridigxListigxCard组件使用。

Rx.js allows us to cache the result of the HTTP Request. We retrieve this data initially, cache it and use the cached version during the application’s lifetime. The combination of publishReply(1, 300000) and refCount() does the following.

Rx.js允许我们缓存HTTP请求的结果。 我们首先检索此数据,对其进行缓存,并在应用程序的生命周期内使用缓存的版本。 publishReply(1, 300000)refCount()执行以下操作。

publishReply(1, 300000) tells Rx to cache the latest emitted value and to stay valid for 5 minutes. After that time, it will invalidate the cache.

publishReply(1,300000)告诉Rx缓存最新发出的值并保持有效5分钟。 在那之后,它将使缓存无效。

refCount() tells Rx to keep the Observable alive as long as there are any Subscribers.

refCount()告诉Rx只要有任何订阅服务器,就保持Observable处于活动状态。

Now after we subscribe to the Coins list, the result will be cached, and we won’t need to make another HTTP Request.

现在,当我们订阅硬币列表之后,结果将被缓存,并且我们不需要发出另一个HTTP请求。

BlockItem服务 (BlockItem service)

Portfolio Crypto Coins data is ensured by getItemsList() method that returns Observable BlockItem array to which the igxGrid component is subscribed to. Only authenticated users can use this service because of the AngularFireList that we manipulate is associated with unique user ids.

通过返回Observable BlockItem数组的getItemsList()方法确保投资组合加密硬币数据 igxGrid组件订阅的对象。 由于我们操作的AngularFireList与唯一的用户ID相关联,因此只有经过身份验证的用户才能使用此服务。

可视化数据 (Visualize the data)

For the visualization, we use UI Components from the Ignite UI for Angularlibrary. These components are responsible for data handling while providing access to custom templates and real-time updates, with intuitive API, by using minimal amount code.

对于可视化,我们使用Ignite UI for Angular库中的UI组件。 这些组件负责数据处理,同时使用最少的代码通过直观的API提供对自定义模板和实时更新的访问。

igxGrid (igxGrid)

Grids [data] property binding is used to pass the returned BlockItem array. Each <igx-column> represents a field of the object and it is used to define features like editing and sorting. The columns are templatable, and with the help of Angular pipes, we can declare display-value transformations in them easily. We use a decimal pipe to change the minimum number of integer digits before the decimal point.

网格 [data]属性绑定用于传递返回的BlockItem数组。 每个<igx-colu mn>代表对象的一个​​字段,它用于定义诸如编辑和排序之类的功能。 这些列是可模板化的,借助Angular管道的帮助,我们可以轻松地在其中声明显示值转换。 我们使用十进制管道来更改小数点前的最小整数位数。

The component provides straightforward event handlers and API for CRUD operations. Handlers like updateRow and deleteRow are implementing additional logic like AngularFireList manipulation and coin item restore logic with the igxSnackbar.

该组件为CRUD操作提供了直接的事件处理程序和API。 像处理程序updateRowdeleteRow正在实施类似的附加逻辑AngularFireList操纵和硬币项与恢复逻辑igxSnackbar

igx卡 (igxCard)

Cards are used to provide general information of Crypto coins using CSS Flexbox layout. These Card components can be filtered with the igxFilter directive, which can be used to filter different data sources. igxFilter can be applied as a pipe or as a directive.

用于使用CSS Flexbox布局提供加密硬币的常规信息。 可以使用igxFilter指令过滤这些Card组件,该指令可用于过滤不同的数据源。 igxFilter可以用作管道或指令。

igxFinancialChart (igxFinancialChart)

The Chart offers multiple ways in which the data can be visualized and interpreted, once it is returned by the service. There are several display modes for price and volume, and in our case we use chartType=”candle”.

一旦服务返回数据,图表就提供了多种可视化和解释数据的方式。 价格和数量有几种显示模式,在本例中,我们使用chartType=”candle”

The financial chart component analyzes and selects data columns automatically:- Date/Time column to use for x-axis- Open, High, Low, Close, Volume columns or the first 5 numeric columns for y-axis

金融图表组件分析并选择数据列自动: - Date/Time列于使用了x-axis - OpenHighLowCloseVolume列或前5分数值列y-axis

主题化 (Theming)

IgniteUI for Angular bases its component designs on the Material Design Principles and with just a few lines of code, we can easily change the colors, sizes, typography, and overall look and feel of our components.

IgniteUI for Angular的组件设计基于“ 材料设计原则” ,仅需几行代码,我们就可以轻松更改组件的颜色,大小,版式以及整体外观。

Now that we’ve provided all base definitions needed for the igx-theme, and have configured the igx-dark-theme mixin, we need to only apply .light-theme and .dark-theme CSS classes somewhere at DOM element root level and toggle it on button click.

现在,我们已经提供了igx-theme,所需的所有基本定义igx-theme,并配置了igx-dark-theme mixin,我们只需要在DOM元素根目录级别的某个位置应用.light-theme.dark-theme CSS类即可。单击按钮即可切换。

结果 (Result)

结语 (Wrapping up)

Everything is possible with the right tooling. We have created a Portfolio Web application using the full power of the Angular Framework, Firebase Authentication services, and Cloud Database store/synchronization.

使用正确的工具,一切皆有可能。 我们使用Angular Framework,Firebase身份验证服务和Cloud Database存储/同步的全部功能创建了一个Portfolio Web应用程序。

You can find the GitHub repository and the actual portfolio application here.

您可以在此处找到GitHub存储库和实际的投资组合应用程序

Feel free to share in the comments below any questions that you have, suggestions as to what can be improved or changed in the app, or any problems that you’ve encountered while configuring your Firebase account or application.

随时在下面的评论中分享您的任何问题,有关可在应用程序中进行哪些改进或更改的建议,或在配置Firebase帐户或应用程序时遇到的任何问题。

翻译自: https://www.freecodecamp.org/news/firebase-angular-application-with-auth-and-realtime-database-ae37fef5859d/

firebase auth

 类似资料: