®
世界顶尖人才,点播 ®

Toptal, LLC版权所有

\n\n\n\n\n

接下来,我们需要将Firebase模块添加到应用程序中 'firebase' 到AngularJS的列表中 'starter' module:

\n\n
angular.模块('starter', 'ionic', 'starter . '.controllers', 'starter.services', 'firebase'])\n
\n\n

Firebase现在被启用了,就像任何其他AngularJS模块一样.

\n\n

The AngularFire 5分钟教程 会教你在控制器中创建数据引用吗. For our demo app, though, I decided to keep these references in a separate service (since this makes it much easier to maintain and update if the root URL is changed). 要创建此服务,请将以下内容添加到 www/js/services.js:

\n\n
.factory('fireBaseData', function($firebase) {\n    var ref = new Firebase(\"http://luminous-fire-3429.firebaseio.com/\"),\n        refExpenses = new Firebase(\"http://luminous-fire-3429.firebaseio.com/expenses\"),\n        refRoomMates = new Firebase(\"http://luminous-fire-3429.firebaseio.com/room-mates\");\n    return {\n        ref: function() {\n            return ref;\n        },\n        refExpenses: function() {\n            return refExpenses;\n        },\n        refRoomMates: function() {\n            return refRoomMates;\n        }\n    }\n});\n
\n\n

上面的代码添加了三个引用url. 一个用于根,两个用于已命名的集合 expenses and room-mates.

\n\n

Adding a new collection to Firebase is simply done by adding its name to the end of your root URL. So to create the expenses 我们需要的集合,我们只需要以下内容:

\n\n

\nhttp://.firebaseio.com/expenses\n

\n\n

This will create the expenses 集合,然后我们可以开始向其中添加对象.

\n\n

OK, now we can hook in the expenses collection from Firebase to replace the “dummy” expenses array we created earlier. This is done by modifying DashCtrl in www/js/controllers.js as follows:

\n\n
.控制器('DashCtrl', function($scope, fireBaseData, $firebase) {\n    $scope.费用= $firebase(fireBaseData.refExpenses()).$asArray();\n    $scope.addExpense = function(e) {\n        $scope.expenses.$add({\n            by: < someemail > ,\n            label: $scope.label,\n            cost: $scope.cost\n        });\n        $scope.label = \"\";\n        $scope.cost = 0;\n    };
\n    $scope.getTotal = function() {\n        var rtnTotal = 0;\n        for (var i = 0; i < $scope.expenses.length; i++) {\n            rtnTotal += $scope.expenses[i].cost;\n        }\n        return rtnTotal;\n    };\n})\n
\n\n

需要进行一组类似的更改 FriendsCtrl. 我再次建议你尝试自己做这件事, 但是如果你遇到问题, 或者想验证一下你是否做对了, you can refer to my implementation on GitHub.

\n\n

To verify that it’s working, 同时在两个不同的客户端上运行应用程序, add a new expense, 并确保它出现在两个客户端的列表中. If it works… woo-hoo! 现在,您已经成功地将Ionic应用程序与Firebase连接起来了!

\n\n

You can test your multiplatform app on different devices by connecting a device to your system and running ionic run android or ionic emulate ios. 有关的更多信息,请参阅Ionic文档 testing your app.

\n\n

帐户管理和安全与Firebase

\n\n

虽然基本的功能现在正在工作, 一个严重的问题是,我们的应用程序目前完全不安全. The entire world can see your expenses without any permissions or logins being required. 这显然需要解决.

\n\n

Firebase使用“规则”提供了一个强大而简单的身份验证框架。. 使用Firebase的规则语言可以做很多事情. (Refer to the Firebase安全文档 for more detail.)

\n\n

In our case, we will write a very simple rule to block unauthorized users from accessing our data. 要做到这一点,打开你的根URL,点击“安全” & Rules” in your left action bar, paste the code below in your rules, and click Save.

\n\n
{\n    \"rules\": {\n        \".read\": \"auth != null\",\n        \".write\": \"auth != null\"\n    }\n}\n
\n\n

如果现在运行应用程序,您将注意到没有数据. 您甚至可以尝试使用浏览器工具检查您的请求, and you should see a message in your console stating that you are not authorized to view the data.

\n\n

创建用户帐号并启用登录功能

\n\n

You can authenticate your users by letting them create their own email/password combination or use any of their existing Google, Facebook, Twitter, 或Github登录凭据. 用于电子邮件/密码认证, Firebase提供了一套完整的API方法来修改密码, reset, etc. More information about 使用Firebase进行身份验证 可以在Firebase指南中找到.

\n\n

对于我们的演示应用程序,我们将通过Firebase界面创建两个用户帐户. 这可以通过转到您的Firebase根URL并执行以下操作来完成:

\n\n
    \n
  1. Click the Login & Auth在左侧的操作栏.
  2. \n
  3. 选中“启用电子邮件”复选框 & Password Authentication.
  4. \n
  5. 向下滚动找到“添加新帐户表单”
  6. \n
  7. 使用“添加新用户”添加您的帐户.
  8. \n
\n\n

\"Enabling

\n\n

要为用户启用登录界面,首先将以下代码添加到 www/templates/tab-account.html:

\n\n
\n             \n    
\n \n \n \n
\n
\n
You are logged in as {{user.password.email}}
\n
\n \n
\n
\n
\n\n

Then add the following to AccountCtrl in www/controller.js:

\n\n
.控制器('AccountCtrl', function($scope, fireBaseData) {\n    $scope.showLoginForm = false; //Checking if user is logged in\n    $scope.user = fireBaseData.ref().getAuth();\n    if (!$scope.user) {\n        $scope.showLoginForm = true;\n    }\n    //Login method\n    $scope.Login = function (em, pwd) {\n        fireBaseData.ref().authWithPassword({\n            email    : em,\n            password : pwd\n        },函数(错误,authData) {\n            if (error === null) {\n                console.log(\"User ID: \" + authData.uid +\n                            \", Provider: \" + authData.provider);\n                $scope.user = fireBaseData.ref().getAuth();\n                $scope.showLoginForm = false;\n                $scope.$apply();\n            } else {\n                console.log(\"Error authenticating user:\", error);\n            }\n        });\n    };\n\n    // Logout method\n    $scope.logout = function () {\n        fireBaseData.ref().unauth();\n        $scope.showLoginForm = true;\n    };\n});\n
\n\n

从安全的角度来看,需要注意的一件重要的事情是 默认情况下,Firebase登录是持久的. Therefore, 如果您希望用户在每次启动应用程序时都需要登录, 您需要相应地修改Firebase配置. To do this, just one time 登录成功后,执行以下代码:

\n\n
var r = $firebase(fireBaseData . conf.refRoomMates()).$asArray();\n// NOTE: Substitute the email addresses of your two user accounts in the line below\nr.$add([\"user1@mail.com\",\"user2@mail.com\"]);\n
\n\n

You can add this in the account controller after successful login or put a break point after successful login and run it in your console inspector.

\n\n

Filtering Based on User

\n\n

不过,这款多平台移动应用仍缺少一个重要功能. 我们想把你的费用和你室友的费用区分开来. Now that we have created two accounts, we just need to filter the data on our views.

\n\n

我们首先需要修改 dashCtrl in www/js/controllers.js in order to (a) get the data for the current user into $scope and (b) save any added expenses for the current user:

\n\n
.控制器('DashCtrl', function($scope, fireBaseData, $firebase) {\n    $scope.费用= $firebase(fireBaseData.refExpenses()).$asArray();\n    $scope.user = fireBaseData.ref().getAuth();\n    // ADD MESSAGE METHOD\n    $scope.addExpense = function(e) {\n        $scope.expenses.$add({\n            by: $scope.user.password.email,\n            label: $scope.label,\n            cost: $scope.cost\n        });\n        $scope.label = \"\";\n        $scope.cost = 0;\n    };\n    $scope.getTotal = function () {\n        var rtnTotal = 0;\n        for (var i = 0; i < $scope.expenses.length; i++) {\n            rtnTotal += $scope.expenses[i].cost;\n        }\n        return rtnTotal;\n    };\n})\n
\n\n

接下来,我们需要添加一个过滤器 www/templates/tab-dash.html 只显示当前用户的费用:

\n\n
\n
\n\n

好了,主屏幕现在完美了. 用户只能查看和添加自己的费用.

\n\n

The last and final step is to enable sharing of the complete expense list between roommates. To do so, change the www/templates/tab-friends.html to add this filter:

\n\n
\n
\n\n

Then modify FriendsCtrl in www/controllers.js as follows:

\n\n
.控制器('FriendsCtrl', function($scope, fireBaseData, $firebase) {\n    $scope.user = fireBaseData.ref().getAuth();\n    $scope.费用= $firebase(fireBaseData.refExpenses()).$asArray();\n    $scope.roomies = $firebase(fireBaseData.refRoomMates()).$asArray();\n    $scope.roomies.$loaded().then(function(array) {\n        //array = [[set1_rm1_email, set1_rm2_email], [set2_rm1_email, set2_rm2_email] ...]\n        for (var i = 0; i 
\n\n

That’s it! Install/update the app on both your device and your roommate’s device, and you should be all set!

\n\n

Wrap Up

\n\n

Our simple example only begins to scratch the surface of what can be accomplished—and how easily it can be accomplished—using Ionic and Firebase. 他们确实是构建实时内容的强大组合, 使用JavaScript和HTML5的多平台智能手机应用程序.

\n\n
\nRelated: Angular 6教程:新功能 (一个包含Firebase后端的全栈示例)
\n","as":"div","isContentFit":true,"sharingWidget":{"url":"http://ma12.qthklwl.com/front-end/building-multi-platform-real-time-mobile-applications-using-ionic-framework-and-firebase","title":"多平台移动开发:Ionic框架 & Firebase","text":null,"providers":["linkedin","twitter","facebook"],"gaCategory":null,"domain":{"name":"developers","title":"Engineering","vertical":{"name":"developers","title":"Developers","publicUrl":"http://ma12.qthklwl.com/developers"},"publicUrl":"http://ma12.qthklwl.com/developers/blog"},"hashtags":"JavaScript,AngularJS,Real-time,Ionic,Cordova,HTML5,PhoneGap,Hybrid,Firebase"}} " class="hidden">艾瑞网数据报告