firebase auth_如何使用auth和实时数据库构建Firebase Angular应用
firebase auth
by Zdravko Kolev
通過(guò)Zdravko Kolev
如何使用auth和實(shí)時(shí)數(shù)據(jù)庫(kù)構(gòu)建Firebase Angular應(yīng)用 (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.
長(zhǎng)期以來(lái),我一直在尋找一個(gè)好的Portfolio Web應(yīng)用程序,該應(yīng)用程序可以幫助我輕松跟蹤我的加密貨幣盈虧,直到我決定借助Firebase和Angular自行開(kāi)發(fā)此類(lèi)資產(chǎn)! 是的,就是這么簡(jiǎn)單,讓我向您解釋原因。
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為具有用戶(hù)身份驗(yàn)證和實(shí)時(shí)數(shù)據(jù)庫(kù)存儲(chǔ)需求的應(yīng)用程序提供了完美的工具。 它提供了豐富的文檔以及各種開(kāi)發(fā)示例,以幫助任何人更好地了解如何創(chuàng)建出色的應(yīng)用程序。
I have covered the Angular application bootstrapping, using Ignite UI CLI, in another blog post.
我已經(jīng)在另一篇博客文章中介紹了使用Ignite UI CLI引導(dǎo)Angular應(yīng)用程序。
This article aims to:
本文旨在:
- Go through the Firebase installation and setup. 完成Firebase的安裝和設(shè)置。
- Set up Firebase Authentication. 設(shè)置Firebase身份驗(yàn)證。
Implement Real-time database storing and synchronization.
實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)庫(kù)存儲(chǔ)和同步。
- Add Observable data services. 添加可觀察的數(shù)據(jù)服務(wù)。
Visualize the data in an Angular application.
在Angular應(yīng)用程序中可視化數(shù)據(jù) 。
配置Firebase帳戶(hù) (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.
我想完成設(shè)置投資組合Firebase帳戶(hù)所采取的步驟。 通過(guò)選擇添加新項(xiàng)目從Firebase控制臺(tái)創(chuàng)建項(xiàng)目。 提交創(chuàng)建項(xiàng)目表單后,您將看到以下項(xiàng)目概述。
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.
在“項(xiàng)目概述”部分下,您可以找到用于身份驗(yàn)證和數(shù)據(jù)存儲(chǔ)的所有開(kāi)發(fā)工具。 還可以找到投資組合Web應(yīng)用程序中使用的配置。 通過(guò)將Add Firebase添加到您的Web應(yīng)用程序來(lái)生成此配置,然后將其添加到應(yīng)用程序的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.
讓我們回到左側(cè)的邊欄中,然后選擇身份驗(yàn)證 。 從這里,我們可以訪(fǎng)問(wèn)應(yīng)用程序中所需的登錄方法 。 導(dǎo)航到“登錄”選項(xiàng)卡,您可以在“投資組合”應(yīng)用程序中看到已啟用和使用的提供商-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.
登錄提供商可以將用戶(hù)的登錄信息集成到應(yīng)用中,從而使用戶(hù)可以使用其Facebook和Google帳戶(hù)向Firebase進(jìn)行身份驗(yàn)證。 對(duì)于電子郵件/密碼提供程序,它僅使用電子郵件和密碼表示一種簡(jiǎn)單的身份驗(yàn)證機(jī)制。 Firebase Auth提供了內(nèi)置的驗(yàn)證規(guī)則來(lái)驗(yàn)證用戶(hù)條目,因此我們無(wú)需在此處進(jìn)行其他配置。
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提供程序配置,因?yàn)槲覀冃枰粋€(gè)Facebook應(yīng)用程序才能對(duì)登錄進(jìn)行身份驗(yàn)證。 我們已經(jīng)從Facebook Developers創(chuàng)建了FB應(yīng)用,該應(yīng)用為我們提供了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提供程序時(shí), API ID和Secret均應(yīng)填寫(xiě)。 至于Auth重定向URI (從提供者窗口),應(yīng)將其粘貼在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.
讓我們繼續(xù)使用Firebase控制臺(tái)。 從數(shù)據(jù)庫(kù)視圖頁(yè)面,我們創(chuàng)建了一個(gè)實(shí)時(shí)數(shù)據(jù)庫(kù)。
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:
在此視圖中,我們可以找到有關(guān)應(yīng)用程序數(shù)據(jù)項(xiàng)和寫(xiě)入/讀取安全規(guī)則的信息。 以下是投資組合應(yīng)用程序使用的規(guī)則:
{ "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.
此安全規(guī)則配置將僅允許經(jīng)過(guò)身份驗(yàn)證的用戶(hù)讀取和寫(xiě)入我們的數(shù)據(jù)庫(kù)。 如果您想學(xué)習(xí)如何定義更高級(jí)的規(guī)則,強(qiáng)烈建議您查看“ 官方安全和規(guī)則”部分。
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.
好吧,我們?cè)谀睦?#xff1f; 現(xiàn)在,我們已經(jīng)完成了投資組合 Firebase帳戶(hù)的創(chuàng)建,讓我們看看Firebase開(kāi)發(fā)項(xiàng)目是如何創(chuàng)建的。
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.
如果我們還沒(méi)有創(chuàng)建項(xiàng)目,那么我建議您從安裝firebase CLI開(kāi)始 ,它提供了多種工具來(lái)管理和部署Firebase項(xiàng)目。 但是,我們已經(jīng)使用Ignite UI CLI引導(dǎo)了Portfolio Angular項(xiàng)目 ,因此我們只需要從npm安裝AngularFire和Firebase 。 我們需要兩個(gè)軟件包才能與Firebase進(jìn)行通信。 AngularFire是Firebase和Angular開(kāi)發(fā)的官方庫(kù)。
npm install firebase @angular/fire --saveAll AngularFire modules that are used in the application are added in the app.module.ts file:
應(yīng)用程序中使用的所有AngularFire模塊都添加到app.module.ts文件中:
FirestoreModule is needed for the database features like working with collections, queries, and services for data streaming and manipulation.
數(shù)據(jù)庫(kù)功能(例如與集合,查詢(xún)和數(shù)據(jù)流和處理服務(wù)一起使用)需要FirestoreModule 。
FireAuthModule is needed for authentication features like monitoring authentication state, Log-in providers and security.
FireAuthModule是 監(jiān)視身份驗(yàn)證狀態(tài),登錄提供程序和安全性等身份驗(yàn)證功能所需的。
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允許我們使用實(shí)時(shí)數(shù)據(jù)庫(kù)。 對(duì)于需要實(shí)時(shí)在客戶(hù)端之間同步狀態(tài)的移動(dòng)和Web應(yīng)用程序,它非常高效。
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.
組合應(yīng)用程序中未使用的唯一通用模塊是AngularFireStorageModule。 您可以使用此模塊快速,輕松地存儲(chǔ)和提供用戶(hù)生成的內(nèi)容(例如照片和視頻),并監(jiān)視與文件關(guān)聯(lián)的上載和元數(shù)據(jù)。
Now that we know how the app was configured initially, we can take a look at the other Firebase features that are used.
現(xiàn)在我們知道了應(yīng)用程序的最初配置方式,接下來(lái)我們可以看看所使用的其他Firebase功能 。
認(rèn)證方式 (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服務(wù) 監(jiān)視應(yīng)用程序身份驗(yàn)證狀態(tài)。 AngularFireAuth.auth返回一個(gè)初始化firebase.auth.Auth實(shí)例,讓我們的用戶(hù)登錄和退出。 該應(yīng)用程序使用三種提供程序來(lái)演示登錄功能: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.
將為每個(gè)與該用戶(hù)鏈接的提供程序保留Firebase用戶(hù)實(shí)例,并且當(dāng)用戶(hù)注冊(cè)或登錄時(shí),該用戶(hù)將成為Auth實(shí)例的當(dāng)前用戶(hù)。 該實(shí)例將保持用戶(hù)的狀態(tài),因此刷新頁(yè)面或重新啟動(dòng)應(yīng)用程序不會(huì)丟失用戶(hù)的信息。
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.
我們對(duì)Facebook和Google提供程序都使用signInWithRedirect方法,以便通過(guò)重定向到登錄頁(yè)面進(jìn)行登錄。 基于密碼的帳戶(hù)創(chuàng)建用于電子郵件登錄提供程序createUserWithEmailAndPassword 和signInWithEmailAndPassword 是負(fù)責(zé)創(chuàng)建和登錄用戶(hù)帳戶(hù)的方法。
I recommend the official Firebase docs for more detailed information on authentication and user lifecycle.
我建議使用Firebase官方文檔,以獲取有關(guān)身份驗(yàn)證和用戶(hù)生命周期的更多詳細(xì)信息。
實(shí)時(shí)數(shù)據(jù)庫(kù)操作 (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提供了兩個(gè)基于云的,客戶(hù)端可訪(fǎng)問(wèn)的數(shù)據(jù)庫(kù)解決方案,并且我們正在使用Firebase的原始數(shù)據(jù)庫(kù)-Realtime。 在官方文檔頁(yè)面上查看Realtime和Cloud firestore之間的區(qū)別。
AngularFireDatabase and AngularFireList services are used in the Portfolio app to retrieve, save and remove data easily.
AngularFireDatabase 和AngularFireList 組合應(yīng)用程序中使用服務(wù)來(lái)輕松檢索,保存和刪除數(shù)據(jù)。
AngularFireDatabase can be injected through the constructor of a component or @Injectable() service. In our case we use the second approach:
AngularFireDatabase 可以通過(guò)組件的構(gòu)造函數(shù)或@Injectable()注入 服務(wù)。 在我們的例子中,我們使用第二種方法 :
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.
通過(guò)AngularFireDatabase檢索數(shù)據(jù) 服務(wù),該服務(wù)填充BlockItems Observable列表。 AngularFire 提供諸如snapshotChanges()類(lèi)的方法,這些方法以同步數(shù)組的形式返回Observable數(shù)據(jù)。 如果要限制事件動(dòng)作(例如添加 , 更改 , 刪除和移動(dòng)) ,這非常方便。 默認(rèn)情況下,它會(huì)監(jiān)聽(tīng)全部四個(gè)事件,但是,您可能只對(duì)其中一個(gè)事件感興趣,并且可以指定要使用的事件。 在我們的應(yīng)用程序中,我們已訂閱所有這些。
Adding a new item, updating an existing one, or removing it from the list is achieved by using push(), update() and remove() methods.
通過(guò)使用push() , update()和remove()方法,可以添加新項(xiàng)目,更新現(xiàn)有項(xiàng)目或?qū)⑵鋸牧斜碇衦emove() 。
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.
每個(gè)數(shù)據(jù)操作方法都返回一個(gè)Promise,盡管我們不需要使用完成Promise來(lái)表示成功,因?yàn)閷?shí)時(shí)數(shù)據(jù)庫(kù)使列表保持同步。
可觀察的 (Observables)
CoinItem服務(wù) (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服務(wù)使用Observables管理異步數(shù)據(jù)并一次發(fā)出多個(gè)值。 我們使用HttpClient get( )方法從資源中請(qǐng)求數(shù)據(jù)并進(jìn)行訂閱,以便將其轉(zhuǎn)換為CoinItem Observable Array 對(duì)象,稍后將由我們的igxGrid , igxList和igxCard組件使用。
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請(qǐng)求的結(jié)果。 我們首先檢索此數(shù)據(jù),對(duì)其進(jìn)行緩存,并在應(yīng)用程序的生命周期內(nèi)使用緩存的版本。 publishReply(1, 300000)和refCount()執(zhí)行以下操作。
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緩存最新發(fā)出的值并保持有效5分鐘。 在那之后,它將使緩存無(wú)效。
refCount() tells Rx to keep the Observable alive as long as there are any Subscribers.
refCount()告訴Rx只要有任何訂閱服務(wù)器,就保持Observable處于活動(dòng)狀態(tài)。
Now after we subscribe to the Coins list, the result will be cached, and we won’t need to make another HTTP Request.
現(xiàn)在,當(dāng)我們訂閱硬幣列表之后,結(jié)果將被緩存,并且我們不需要發(fā)出另一個(gè)HTTP請(qǐng)求。
BlockItem服務(wù) (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.
通過(guò)返回Observable BlockItem數(shù)組的getItemsList()方法確保投資組合加密硬幣數(shù)據(jù) igxGrid組件訂閱的對(duì)象。 由于我們操作的AngularFireList與唯一的用戶(hù)ID相關(guān)聯(lián),因此只有經(jīng)過(guò)身份驗(yàn)證的用戶(hù)才能使用此服務(wù)。
可視化數(shù)據(jù) (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.
對(duì)于可視化,我們使用Ignite UI for Angular庫(kù)中的UI組件。 這些組件負(fù)責(zé)數(shù)據(jù)處理,同時(shí)使用最少的代碼通過(guò)直觀的API提供對(duì)自定義模板和實(shí)時(shí)更新的訪(fǎng)問(wèn)。
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.
網(wǎng)格 [data]屬性綁定用于傳遞返回的BlockItem數(shù)組。 每個(gè)<igx-colu mn>代表對(duì)象的一個(gè)??字段,它用于定義諸如編輯和排序之類(lèi)的功能。 這些列是可模板化的,借助Angular管道的幫助,我們可以輕松地在其中聲明顯示值轉(zhuǎn)換。 我們使用十進(jìn)制管道來(lái)更改小數(shù)點(diǎn)前的最小整數(shù)位數(shù)。
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。 像處理程序updateRow和deleteRow正在實(shí)施類(lèi)似的附加邏輯AngularFireList操縱和硬幣項(xiàng)與恢復(fù)邏輯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布局提供加密硬幣的常規(guī)信息。 可以使用igxFilter指令過(guò)濾這些Card組件,該指令可用于過(guò)濾不同的數(shù)據(jù)源。 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”.
一旦服務(wù)返回?cái)?shù)據(jù),圖表就提供了多種可視化和解釋數(shù)據(jù)的方式。 價(jià)格和數(shù)量有幾種顯示模式,在本例中,我們使用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
金融圖表組件分析并選擇數(shù)據(jù)列自動(dòng): - Date/Time列于使用了x-axis - Open , High , Low , Close , Volume列或前5分?jǐn)?shù)值列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的組件設(shè)計(jì)基于“ 材料設(shè)計(jì)原則” ,僅需幾行代碼,我們就可以輕松更改組件的顏色,大小,版式以及整體外觀。
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.
現(xiàn)在,我們已經(jīng)提供了igx-theme,所需的所有基本定義igx-theme,并配置了igx-dark-theme mixin,我們只需要在DOM元素根目錄級(jí)別的某個(gè)位置應(yīng)用.light-theme和.dark-theme CSS類(lèi)即可。單擊按鈕即可切換。
結(jié)果 (Result)
結(jié)語(yǔ) (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身份驗(yàn)證服務(wù)和Cloud Database存儲(chǔ)/同步的全部功能創(chuàng)建了一個(gè)Portfolio Web應(yīng)用程序。
You can find the GitHub repository and the actual portfolio application here.
您可以在此處找到GitHub存儲(chǔ)庫(kù)和實(shí)際的投資組合應(yīng)用程序 。
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.
隨時(shí)在下面的評(píng)論中分享您的任何問(wèn)題,有關(guān)可在應(yīng)用程序中進(jìn)行哪些改進(jìn)或更改的建議,或在配置Firebase帳戶(hù)或應(yīng)用程序時(shí)遇到的任何問(wèn)題。
翻譯自: https://www.freecodecamp.org/news/firebase-angular-application-with-auth-and-realtime-database-ae37fef5859d/
firebase auth
總結(jié)
以上是生活随笔為你收集整理的firebase auth_如何使用auth和实时数据库构建Firebase Angular应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 梦到和前男友吵架是什么意思啊
- 下一篇: kotlin数据库_如何在Kotlin应