在本系列教程的最后一部分 ,您了解了如何编写用于用户登录的REST API端点。 您使用Mongoose从Node与MongoDB进行了交互。 成功验证之后,您将看到如何使用Angular Router
导航到HomeComponent
。
在本系列教程的这一部分中,您将创建一个组件,以在主页上列出博客文章的详细信息。
入门
让我们从克隆本系列最后一部分的源代码开始。
git clone https://github.com/royagasthyan/AngularBlogApp-Home AngularBlogApp-Post
导航到项目目录并安装所需的依赖项。
cd AngularBlogApp-Post/client
npm install
cd AngularBlogApp-Post/server
npm install
安装依赖项后,请重新启动客户端和服务器应用程序。
cd AngularBlogApp-Post/client
npm start
cd AngularBlogApp-Post/server
node app.js
将您的浏览器指向http:// localhost:4200 ,您应该正在运行该应用程序。
![Angular Blogging应用](https://i-blog.csdnimg.cn/blog_migrate/3a9b672e3c84b1ea198796eeb893b16e.png)
创建显示帖子组件
用户登录到应用程序后,将显示HomeComponent
。 HomeComponent
充当其内部显示的所有组件的包装器组件。 你会显示由用户添加的博客文章列表HomeComponent
。
为了显示博客文章,让我们创建一个名为ShowPostComponent
的新组件。 在src/app
文件夹内创建一个名为show-post
的文件夹。 在show-post
文件夹中,创建一个名为show-post.component.html
文件,并添加以下HTML代码:
<div class="list-group">
<a href="#" class="list-group-item list-group-item-action flex-column align-items-start active">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">List group item heading</h5>
<small>3 days ago</small>
</div>
<p class="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>
<small>Donec id elit non mi porta.</small>
</a>
<a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">List group item heading</h5>
<small class="text-muted">3 days ago</small>
</div>
<p class="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>
<small class="text-muted">Donec id elit non mi porta.</small>
</a>
<a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">List group item heading</h5>
<small class="text-muted">3 days ago</small>
</div>
<p class="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>
<small class="text-muted">Donec id elit non mi porta.</small>
</a>
</div>
创建一个名为文件show-post.component.ts
其中将包含ShowPostComponent
类。 外观如下:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-show-post',
templateUrl: './show-post.component.html'
})
export class ShowPostComponent implements OnInit {
constructor() {
}
ngOnInit(){
}
}
导入ShowPostComponent
在app.module.ts
文件。
import { ShowPostComponent } from './show-post/show-post.component';
添加ShowPostComponent
在NgModule
在app.module.ts
文件。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ROUTING } from './app.routing';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RootComponent } from './root/root.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { ShowPostComponent } from './show-post/show-post.component';
@NgModule({
declarations: [
RootComponent,
LoginComponent,
HomeComponent,
ShowPostComponent
],
imports: [
BrowserModule,
ROUTING,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [RootComponent]
})
export class AppModule { }
修改home.component.html
文件,包括ShowPostComponent
选择。
<app-show-post></app-show-post>
这是修改后的home.component.html
文件的外观:
<header class="header clearfix">
<nav>
<ul class="nav nav-pills float-right">
<li class="nav-item">
<button type="button" class="btn btn-primary">
Home
</button>
</li>
<li class="nav-item">
<button type="button" class="btn btn-link" data-toggle="modal" data-target="#exampleModal">
Add
</button>
</li>
<li class="nav-item">
<button type="button" class="btn btn-link">
Logout
</button>
</li>
</ul>
</nav>
<h3 class="text-muted">Angular Blog App</h3>
</header>
<main role="main">
<app-show-post></app-show-post>
</main>
<footer class="footer">
<p>© Company 2017</p>
</footer>
保存以上更改并刷新客户端应用程序。 登录该应用程序后,您将能够查看列出的博客文章。
![Angular Blog App-显示帖子组件](https://i-blog.csdnimg.cn/blog_migrate/63edc928f536086b80b039b4cd5b812c.png)
创建Show Post组件服务
ShowPostComponent
服务中显示的数据显示硬编码的数据。 您需要一种服务来从MongoDB数据库中查询博客文章列表。 让我们为ShowPostComponent
创建一个服务。
在src/app/show-post
创建一个名为show-post.service.ts
的文件,并添加以下代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ShowPostService {
constructor(private http: HttpClient){
}
}
里面ShowPostService
,创建一个名为方法getAllPost
,这将使得REST API调用来获取博客文章列表。 外观如下:
getAllPost(){
return this.http.post('/api/post/getAllPost',{})
}
这是show-post.service.ts
文件的外观:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from '../models/post.model';
@Injectable()
export class ShowPostService {
constructor(private http: HttpClient){
}
getAllPost(){
return this.http.post('/api/post/getAllPost',{})
}
}
接下来,您需要写下REST API来查询MongoDB集合以获取博客文章列表。
在服务器端,让我们开始为帖子创建模型。 在models
文件夹中,创建一个名为post.js
的文件。 需要Mongoose
模块并为博客文章创建一个架构,然后将其导出。 这是/server/models/post.js
外观:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// create a schema
const postSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true }
}, { collection : 'post' });
const Post = mongoose.model('Post', postSchema);
module.exports = Post;
将上述定义的post.js
文件导出到app.js
。
const Post = require('./model/post');
创建一个API端点/api/post/getAllPost
来获取博客文章列表。 使用mongoose
客户端连接到MongoDB数据库。
app.post('/api/post/getAllPost', (req, res) => {
mongoose.connect(url, { useMongoClient: true } , function(err){
if(err) throw err;
console.log('connection established successfully');
});
})
建立连接后,就可以使用“ Post
模型查找博客帖子的列表。
Post.find({},[],{},(err, doc) => {
if(err) throw err;
console.log('result is ',doc);
})
.find
回调返回文档列表。
返回的文档将按升序排列,因此添加一个条件以按降序对博客文章进行排序。
Post.find({},[],{ sort: { _id: -1 } },(err, doc) => {
if(err) throw err;
})
从数据库查询完文档列表后,返回数据和status
。 REST API的外观如下:
app.post('/api/post/getAllPost', (req, res) => {
mongoose.connect(url, { useMongoClient: true } , function(err){
if(err) throw err;
Post.find({},[],{ sort: { _id: -1 } },(err, doc) => {
if(err) throw err;
return res.status(200).json({
status: 'success',
data: doc
})
})
});
})
进行API调用
在show-post.component.ts
文件中,定义一个数组列表以保留API调用的结果。
public posts : any [];
导入ShowPostService
在ShowPostComponent
。
import { ShowPostService } from './show-post.service';
将ShowPostService
作为提供程序添加到ShowPostComponent
。
@Component({
selector: 'app-show-post',
templateUrl: './show-post.component.html',
styleUrls: ['./show-post.component.css'],
providers: [ ShowPostService ]
})
定义一个名为getAllPost
的方法来调用服务方法。 外观如下:
getAllPost(){
this.showPostService.getAllPost().subscribe(result => {
this.posts = result['data'];
});
}
如上面的代码所示,结果数据被设置为posts
变量。
从ngOnInit
方法调用上述定义的方法,以便在组件初始化后立即获取博客文章详细信息。
ngOnInit(){
this.getAllPost();
}
这是show-post.component.ts
文件的外观:
import { Component, OnInit } from '@angular/core';
import { ShowPostService } from './show-post.service';
@Component({
selector: 'app-show-post',
templateUrl: './show-post.component.html',
styleUrls: ['./show-post.component.css'],
providers: [ ShowPostService ]
})
export class ShowPostComponent implements OnInit {
public posts : any [];
constructor(private showPostService: ShowPostService) {
}
ngOnInit(){
this.getAllPost();
}
getAllPost(){
this.showPostService.getAllPost().subscribe(result => {
this.posts = result['data'];
});
}
}
渲染博客文章
MongoDB集合可能没有要查询的条目。 因此,让我们从mongo
shell中在MongoDB中添加一些条目。
通过输入以下命令来输入MongoDB Shell:
mongo
输入mongo
shell后,检查MongoDB数据库中可用的数据库。
show collections;
从列出的条目中选择blogDb
数据库。
use blogDb
创建一个名为post
的集合。
db.createCollection('post')
在post
集合中插入几个条目。
db.post.insert(
{ title : 'TutsPlus Python Entry',
description : 'Welcome to official entry of TutsPlus Python programming session'
}
)
现在,让我们将ShowPostComponent
中的posts
变量绑定到HTML代码。
您将使用ngFor
指令来迭代posts
变量并显示博客文章。 修改show-post.component.html
文件,如下所示:
<div class="list-group">
<a *ngFor="let post of posts" href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{post.title}}</h5>
<small>3 days ago</small>
</div>
<p class="mb-1">{{post.description}}</p>
<small>read more...</small>
</a>
</div>
保存以上更改,然后重新启动客户端和REST API服务器。 登录该应用程序,您将在主页上显示MongoDB插入的记录。
![Angular Blog App-动态博客发布列表](https://i-blog.csdnimg.cn/blog_migrate/66e926611085b86d8ee33f25d49b76bb.png)
包起来
在本教程中,您创建了ShowPostComponent
来显示MongoDB
数据库中的博客文章详细信息。 您创建了REST API,用于使用Node服务器中的Mongoose
客户端查询MongoDB数据库。
在本系列教程的下一部分中,您将学习如何创建AddPostComponent
来从应用程序用户界面添加新帖子。
到目前为止,您的情况如何? 请在下面的评论中让我知道您的宝贵建议。