Table of Contents
start using
Building data in Firebase
Rendering posts on the welcome page
Query data from Firebase
使用AngularJS绑定查询结果
修复几个小问题
创建帖子后重定向
链接欢迎页面以添加帖子
结论
Home Web Front-end HTML Tutorial Building web applications with AngularJS and Firebase: Part 5

Building web applications with AngularJS and Firebase: Part 5

Sep 01, 2023 pm 02:21 PM

In the previous part of this series, we designed and implemented an interface to create blog posts with titles and posts. In this part, we'll see how to get a saved blog post in Firebase and render it on our welcome page.

start using

We start by cloning the previous part of this tutorial from GitHub.

git clone https://github.com/jay3dec/AngularJS_Firebase_Part4.git
Copy after login

After cloning the source code, navigate to the project directory and install the required dependencies.

cd AngularJS_Firebase_Part4
npm install
Copy after login

After installing the dependencies, start the server

npm start
Copy after login

Point your browser to http://localhost:8000/app/#/home and the application should be running.

Building data in Firebase

Previously when we were inserting data into Firebase we were just pushing the data to the Firebase URL and it would be randomly listed in Firebase. However, when the data grows and everything is pushed to Firebase, maintaining the data becomes difficult. So we'll try to organize the data in a way that will make Firebase queries easier.

Log in to Firebase and go to Manage Apps. You should see the Firebase URL on the dashboard screen like this:

使用 AngularJS 和 Firebase 构建 Web 应用程序:第 5 部分

Click the plus icon next to URL and create a child node named Articles with a value of 0 and click Add. After adding the child nodes, you should see something similar to the following:

使用 AngularJS 和 Firebase 构建 Web 应用程序:第 5 部分

As you can see, we have separately classified the article data, which makes it easier to query and obtain data.

Now, navigate to addPost.js and change the Firebase URL to https://blistering-heat-2473.firebaseio.com/Articles. We also add the email ID of the user associated with the blog post. We can get the email ID from the CommonProp service we wrote earlier. Just inject the CommonProp service in the AddPostCtrl controller.

.controller('AddPostCtrl', ['$scope','$firebase','CommonProp',function($scope,$firebase,CommonProp) {
Copy after login

When pushing data, also include the email ID parameter. Here is the modified AddPost function:

$scope.AddPost = function() {
    var title = $scope.article.title;
    var post = $scope.article.post;

    var firebaseObj = new Firebase("https://blistering-heat-2473.firebaseio.com/Articles");
    var fb = $firebase(firebaseObj);

    fb.$push({
        title: title,
        post: post,
        emailId: CommonProp.getUser()
    }).then(function(ref) {
        console.log(ref);
    }, function(error) {
        console.log("Error:", error);
    });

}
Copy after login

Save all changes and restart the server. Try logging in with a valid email address and password and creating a blog post. Now, if you look at the Firebase dashboard, you should see the post details in the Articles child node, like this:

使用 AngularJS 和 Firebase 构建 Web 应用程序:第 5 部分

Rendering posts on the welcome page

Next, let’s add a Bootstrap list group component to display user-created posts. Navigate to app/welcome/welcome.html and in a div with class container, add a list group component after the welcome message like this:

<div class="list-group">
    <a href="#" class="list-group-item active">
        <h4 class="list-group-item-heading">Title Heading</h4>
        <p class="list-group-item-text">Blog post content </p>
    </a>
</div>
Copy after login
Copy after login

Save changes and restart the server. Try logging in with a valid email address and password. On the welcome page, you should see something similar to the following:

使用 AngularJS 和 Firebase 构建 Web 应用程序:第 5 部分

Query data from Firebase

Next, we query the data from Firebase using the URL https://blistering-heat-2473.firebaseio.com/Articles.

Open welcome.js and create a Firebase object with the above URL inside the WelcomeCtrl controller.

var firebaseObj = new Firebase("https://blistering-heat-2473.firebaseio.com/Articles");
Copy after login

We will use $firebase to get data from Firebase. According to official documentation:

$firebase Wrapper used to synchronize Firebase data with Angular applications. It contains helper methods for writing data to Firebase, as well as tools for reading data into a synchronized collection or object.
var sync = $firebase(firebaseObj);
Copy after login

To get data from a Firebase URL as a synchronized array, AngularFire provides a method called $asArray. Let's call the $asArray method on the sync object and assign it to another $scope variable.

$scope.articles = sync.$asArray();
Copy after login

Also add a paragraph element to the welcome page like this:

<p>{{articles}}</p>
Copy after login

Save all changes and restart the server. Log in using a valid email address and password. After entering the welcome page, you should get the query results in the form of JSON data in the $scope.articles binding element.

[{
    "emailId": "jim@jim.com",
    "post": "This is my first post on this platform.",
    "title": "Hello !!"
}, {
    "emailId": "jim@jim.com",
    "post": "Good night for tonight",
    "title": "GoodBye"
}]
Copy after login

使用AngularJS绑定查询结果

由于我们在 $scope.articles 变量中拥有从 Firebase 查询的数据,因此我们可以将数据绑定到欢迎页面列表元素。我们将使用 AngularJS 指令 ngRepeat 在 Bootstrap 列表组中重复数据。以下是列表组 HTML:

<div class="list-group">
    <a href="#" class="list-group-item active">
        <h4 class="list-group-item-heading">Title Heading</h4>
        <p class="list-group-item-text">Blog post content </p>
    </a>
</div>
Copy after login
Copy after login

ngRepeat 指令添加到主 div 中,如图所示。

ng-repeat="article in articles"
Copy after login

ngRepeat 指令迭代articles 变量并在列表组div 中为每个项目创建HTML。因此,修改显示的 HTML 代码:

<div class="list-group" ng-repeat="article in articles">
    <a href="#" class="list-group-item active">
        <h4 class="list-group-item-heading">{{article.title}}</h4>
        <p class="list-group-item-text">{{article.post}}</p>
    </a>
</div>
Copy after login

保存更改并重新启动服务器。使用电子邮件地址和密码登录,进入欢迎页面后,您应该会看到从“添加帖子”页面添加的文章列表。

使用 AngularJS 和 Firebase 构建 Web 应用程序:第 5 部分

现在导航至 http://localhost:8000/app/#/addPost 并添加另一篇帖子。由于我们在创建帖子后尚未添加到欢迎页面的重定向,因此请手动导航到 http://localhost:8000/app/#/welcome,您应该会在列表中看到它。

修复几个小问题

创建帖子后重定向

添加帖子后,我们需要将用户重定向到欢迎页面。打开 app/addPost/addPost.js 并在 AddPostCtrl 控制器中注入 $location 。在 fb.$push 成功回调中,添加重定向到 welcome 页面。

fb.$push({
    title: title,
    post: post,
    emailId: CommonProp.getUser()
}).then(function(ref) {
    console.log(ref);
    $location.path('/welcome');
}, function(error) {
    console.log("Error:", error);
});
Copy after login

链接欢迎页面以添加帖子

打开 app/welcome/welcome.html 并修改添加帖子链接 href 重定向到添加帖子页面,如图所示:

<a class="blog-nav-item " href="#/addPost">Add Post</a>
Copy after login

保存所有更改并重新启动服务器。使用有效的电子邮件地址和密码登录并尝试创建帖子,您应该能够在欢迎页面列表中查看该帖子。

结论

在本教程中,我们了解了如何使用 AngularFire 查询 Firebase 中存储的数据。我们创建了一个界面,将用户创建的博客文章呈现为欢迎页面上的列表。我们还修复了一些小问题。

在本系列的下一部分中,我们将通过实现更多功能(例如编辑和删除博客文章)将其提升到新的水平。

本教程的源代码可在 GitHub 上获取。请在下面的评论中告诉我们您的想法!

The above is the detailed content of Building web applications with AngularJS and Firebase: Part 5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

See all articles