• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

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

在教程系列的最后一部分中,您看到了如何编写用于用户登录的rest api端点。您使用 mongoosenodemongodb交互。成功验证后,您看到了如何使用 angular导航到 .RouterHomeComponent

在本教程系列的这一部分中,您将创建一个组件来在主页上列出博客文章的详细信息。

入门

让我们从克隆教程系列最后一部分的源代码开始。

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和 MongoDB创建博客应用程序:显示帖子  第1张

创建 Show Post 组件

用户登录应用程序后,您将显示HomeComponentHomeComponent对于显示在其中的所有组件,它就像一个包装组件。您将在HomeComponent.

为了显示博客文章,让我们创建一个名为ShowPostComponentshow-post在文件夹内创建一个名为的src/app文件夹。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';

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

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

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

创建 Show Post 组件服务

服务中显示的数据ShowPostComponent显示硬编码数据。您需要一项服务来从 MongoDB 数据库中查询博客文章列表。让我们为您的ShowPostComponent.

创建一个名为show-post.service.tsin的文件src/app/show-post并添加以下代码:

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

进入mongoshell 后,检查 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'
    }
)

现在让我们将posts变量绑定ShowPostComponent到 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和 MongoDB创建博客应用程序:显示帖子  第3张

把它包起来

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



文章目录
  • 入门
  • 创建 Show Post 组件
  • 创建 Show Post 组件服务
  • 进行 API 调用
  • 渲染博客文章
  • 把它包起来