使用Angular和MongoDB创建博客应用程序:显示帖子

在本系列教程的最后一部分 ,您了解了如何编写用于用户登录的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应用

创建显示帖子组件

用户登录到应用程序后,将显示HomeComponentHomeComponent充当其内部显示的所有组件的包装器组件。 你会显示由用户添加的博客文章列表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(){
  
  }

}

导入ShowPostComponentapp.module.ts文件。

import { ShowPostComponent } from './show-post/show-post.component';

添加ShowPostComponentNgModuleapp.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>&copy; Company 2017</p>
</footer>

保存以上更改并刷新客户端应用程序。 登录该应用程序后,您将能够查看列出的博客文章。

Angular Blog App-显示帖子组件

创建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 [];

导入ShowPostServiceShowPostComponent

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-动态博客发布列表

包起来

在本教程中,您创建了ShowPostComponent来显示MongoDB数据库中的博客文章详细信息。 您创建了REST API,用于使用Node服务器中的Mongoose客户端查询MongoDB数据库。

在本系列教程的下一部分中,您将学习如何创建AddPostComponent来从应用程序用户界面添加新帖子。

本教程的源代码可在GitHub找到

到目前为止,您的情况如何? 请在下面的评论中让我知道您的宝贵建议。

翻译自: https://code.tutsplus.com/tutorials/creating-a-blogging-app-using-angular-mongodb-show-post--cms-30140

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值