博客提交功能将 post 保存到数据库,但不会在 angular 组件中显示博客 post
Blog Submit function saves post to database but won't display blog post in angular component
我正在尝试使用 angular 和 mongodb 创建博客。当我提交我的博客时,它被保存在数据库中(使用邮递员检查)。我在 input 标签和 ckeditor 中输入的数据在我测试时也出现在 mat-card 组件中。但是当我尝试提交博客时,它不会显示在博客页面组件中。博客存储在数据库中。我的 onBlogSubmit() 函数有问题,但我不知道它是什么:
这是我试过的:
我的 post.service.ts 文件:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Post } from '../post/post';
import { Observable, throwError } from 'rxjs';
import 'rxjs/add/operator/map';
export interface post {
success: boolean;
post: any;
token: any;
}
@Injectable({
providedIn: 'root'
})
export class PostService {
authToken: any;
post: any;
public baseUri: string = 'http://localhost:3000/blogs';
public headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private http: HttpClient) { }
getPosts(): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.get<post>(this.baseUri + '/allPosts', { headers: head });
}
getPost(id): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.get<post>(this.baseUri + '/singlePost/' + id, { headers: head })
}
addPost(post): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.post<post>(this.baseUri + '/newPost', post, { headers: head });
}
updatePost(id, post: post): Observable<any> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.put<post>(this.baseUri + '/editPost/' +id , post, { headers: head });
}
deletePost(id): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.put<post>(this.baseUri + '/deletePost/' + id, { headers: head });
}
public loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
我的博客-添加component.ts:
import { Component, OnInit } from '@angular/core';
import { PostService } from '../Services/post.service';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
@Component({
selector: 'app-blog-add',
templateUrl: './blog-add.component.html',
styleUrls: ['./blog-add.component.scss']
})
export class BlogAddComponent implements OnInit {
postTitle: string;
postAuthor: string;
postContent: string;
postImgUrl: string;
post = {};
constructor(private postService: PostService,
private formBuilder: FormBuilder,
private router: Router,
private flashMessage: FlashMessagesService) {
}
ngOnInit(): void {
}
// THIS IS WHERE THE PROBLEM OCCURS
onBlogSubmit() {
const post = {
postTitle: this.postTitle,
postAuthor: this.postAuthor,
postContent: this.postContent,
postImgUrl: this.postImgUrl
}
this.postService.addPost(post).subscribe(data => {
if(data.success) {
this.postService.getPosts();
this.flashMessage.show('Blog Submitted Successfully', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/blog-page']);
} else {
this.flashMessage.show('Something Went Wrong', {cssClass: 'alert-danger', timeout: 3000});
}
});
}
}
我的博客-添加组件HTML:
<app-header></app-header>
<div class="row" *ngIf="post">
<div class="col-sm-12 form-main">
<form name="postForm" (ngsubmit)="onBlogSubmit()" class="text-center border border-light p-5 shadow-lg">
<input type="text" class="form-control mb-4" placeholder="Name" [(ngModel)]="post.postTitle" name="postTitle">
<input type="text" class="form-control mb-4" placeholder="Username" [(ngModel)]="post.postAuthor" name="postAuthor">
<img ng-src="postImgUrl">
<ckeditor matCkeditor class="form-control mb-8" [(ngModel)]="post.postContent" name="postContent"></ckeditor>
<button mat-raised-button type="submit" class="btn btn-success btn-block get" (click)="onBlogSubmit()">Submit</button>
</form>
</div>
</div>
我要查看博客数据的博客页面ts文件。
import { Component, OnInit } from '@angular/core';
import { PostService } from '../Services/post.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-blog-page',
templateUrl: './blog-page.component.html',
styleUrls: ['./blog-page.component.scss']
})
export class BlogPageComponent implements OnInit {
post: Object;
constructor(private postService: PostService, private router: Router) {}
ngOnInit(): void {
this.postService.getPosts().subscribe(posts => {
this.post = posts.post;
},
err => {
console.log(err);
return false;
});
}
}
我的博客页面组件 HTML:
<app-header></app-header>
<div fxLayout="row wrap" fxLayoutAlign="center">
<mat-card *ngIf="post" class="card">
<mat-card-header>
<mat-card-title class="title">{{post.postTitle}}</mat-card-title>
<mat-card-subtitle class="subtitle">Author: {{post.postAuthor}}</mat-card-subtitle>
<mat-card-subtitle class="subtitle">Content: {{post.postContent}}</mat-card-subtitle>
</mat-card-header>
<mat-card-actions class="multi-button">
<button mat-icon-button><span class="fa fa-share fa-lg"></span></button>
<button mat-icon-button><span class="fa fa-trash fa-lg"></span></button>
<!-- <button mat-icon-button><span class="fa fa-heart fa-lg"></span></button> -->
</mat-card-actions>
</mat-card>
</div>
<app-footer></app-footer>
控制台或浏览器中没有错误。该博客只是不提交并给出了我编入其中的错误消息。我一直无法弄清楚问题所在。我已经测试了我在输入和ckeditor中输入的数据是否出现在mat-card模块中并且工作正常。请有人告诉我我在这里做错了什么。谢谢!
由于您调用的端点没有 return .success
属性,因此您无法使用它来确定调用是否成功。
响应中是否有任何其他数据表明它是否成功?
如果不是,也许您可以假设非错误响应是成功的,并在错误处理程序中捕获错误:
onBlogSubmit() {
const post = {
postTitle: this.postTitle,
postAuthor: this.postAuthor,
postContent: this.postContent,
postImgUrl: this.postImgUrl
}
this.postService.addPost(post).subscribe(
data => {
this.postService.getPosts();
this.flashMessage.show('Blog Submitted Successfully', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/blog-page']);
},
error => {
this.flashMessage.show('Something Went Wrong', {cssClass: 'alert-danger', timeout: 3000});
}
);
}
你的blog-page
有问题。
更正:
HTML:
<app-header></app-header>
<div *ngFor="let post of posts" fxLayout="row wrap" fxLayoutAlign="center">
<mat-card class="card">
<mat-card-header>
<mat-card-title class="title">{{post.postTitle}}</mat-card-title>
<mat-card-subtitle class="subtitle">Author: {{post.postAuthor}}</mat-card-subtitle>
<mat-card-subtitle class="subtitle">Content: {{post.postContent}}</mat-card-subtitle>
</mat-card-header>
<mat-card-actions class="multi-button">
<button mat-icon-button><span class="fa fa-share fa-lg"></span></button>
<button mat-icon-button><span class="fa fa-trash fa-lg"></span></button>
<!-- <button mat-icon-button><span class="fa fa-heart fa-lg"></span></button> -->
</mat-card-actions>
</mat-card>
</div>
TypeScript:
import { Component, OnInit } from "@angular/core";
import { PostService } from "../post.service";
import { Router } from "@angular/router";
@Component({
selector: "app-blog-page",
templateUrl: "./blog-page.component.html"
styleUrls: ["./blog-page.component.scss"]
})
export class BlogPageComponent implements OnInit {
posts: Object;
constructor(private postService: PostService, private router: Router) {}
ngOnInit(): void {
this.postService.getPosts().subscribe(
posts => {
console.log(posts);
this.posts = posts;
},
err => {
console.log(err);
return false;
}
);
}
}
在 StackBlitz 进行演示。
注意:我评论了你的一些组件并嘲笑了你的API。请用你真实的API来测试
编辑:
同时更改blog-add
组件的HTML:
<app-header></app-header>
<div class="row" *ngIf="post">
<div class="col-sm-12 form-main">
<form name="postForm" (ngsubmit)="onBlogSubmit()" class="text-center border border-light p-5 shadow-lg">
<input type="text" class="form-control mb-4" placeholder="Name" [(ngModel)]="postTitle" name="postTitle">
<input type="text" class="form-control mb-4" placeholder="Username" [(ngModel)]="postAuthor" name="postAuthor">
<img ng-src="postImgUrl">
<ckeditor matCkeditor class="form-control mb-8" [(ngModel)]="postContent" name="postContent"></ckeditor>
<button mat-raised-button type="submit" class="btn btn-success btn-block get" (click)="onBlogSubmit()">Submit</button>
</form>
</div>
</div>
我正在尝试使用 angular 和 mongodb 创建博客。当我提交我的博客时,它被保存在数据库中(使用邮递员检查)。我在 input 标签和 ckeditor 中输入的数据在我测试时也出现在 mat-card 组件中。但是当我尝试提交博客时,它不会显示在博客页面组件中。博客存储在数据库中。我的 onBlogSubmit() 函数有问题,但我不知道它是什么:
这是我试过的:
我的 post.service.ts 文件:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Post } from '../post/post';
import { Observable, throwError } from 'rxjs';
import 'rxjs/add/operator/map';
export interface post {
success: boolean;
post: any;
token: any;
}
@Injectable({
providedIn: 'root'
})
export class PostService {
authToken: any;
post: any;
public baseUri: string = 'http://localhost:3000/blogs';
public headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private http: HttpClient) { }
getPosts(): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.get<post>(this.baseUri + '/allPosts', { headers: head });
}
getPost(id): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.get<post>(this.baseUri + '/singlePost/' + id, { headers: head })
}
addPost(post): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.post<post>(this.baseUri + '/newPost', post, { headers: head });
}
updatePost(id, post: post): Observable<any> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.put<post>(this.baseUri + '/editPost/' +id , post, { headers: head });
}
deletePost(id): Observable<post> {
this.loadToken();
const head = this.headers.append('Authorization', this.authToken);
return this.http.put<post>(this.baseUri + '/deletePost/' + id, { headers: head });
}
public loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
我的博客-添加component.ts:
import { Component, OnInit } from '@angular/core';
import { PostService } from '../Services/post.service';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
@Component({
selector: 'app-blog-add',
templateUrl: './blog-add.component.html',
styleUrls: ['./blog-add.component.scss']
})
export class BlogAddComponent implements OnInit {
postTitle: string;
postAuthor: string;
postContent: string;
postImgUrl: string;
post = {};
constructor(private postService: PostService,
private formBuilder: FormBuilder,
private router: Router,
private flashMessage: FlashMessagesService) {
}
ngOnInit(): void {
}
// THIS IS WHERE THE PROBLEM OCCURS
onBlogSubmit() {
const post = {
postTitle: this.postTitle,
postAuthor: this.postAuthor,
postContent: this.postContent,
postImgUrl: this.postImgUrl
}
this.postService.addPost(post).subscribe(data => {
if(data.success) {
this.postService.getPosts();
this.flashMessage.show('Blog Submitted Successfully', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/blog-page']);
} else {
this.flashMessage.show('Something Went Wrong', {cssClass: 'alert-danger', timeout: 3000});
}
});
}
}
我的博客-添加组件HTML:
<app-header></app-header>
<div class="row" *ngIf="post">
<div class="col-sm-12 form-main">
<form name="postForm" (ngsubmit)="onBlogSubmit()" class="text-center border border-light p-5 shadow-lg">
<input type="text" class="form-control mb-4" placeholder="Name" [(ngModel)]="post.postTitle" name="postTitle">
<input type="text" class="form-control mb-4" placeholder="Username" [(ngModel)]="post.postAuthor" name="postAuthor">
<img ng-src="postImgUrl">
<ckeditor matCkeditor class="form-control mb-8" [(ngModel)]="post.postContent" name="postContent"></ckeditor>
<button mat-raised-button type="submit" class="btn btn-success btn-block get" (click)="onBlogSubmit()">Submit</button>
</form>
</div>
</div>
我要查看博客数据的博客页面ts文件。
import { Component, OnInit } from '@angular/core';
import { PostService } from '../Services/post.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-blog-page',
templateUrl: './blog-page.component.html',
styleUrls: ['./blog-page.component.scss']
})
export class BlogPageComponent implements OnInit {
post: Object;
constructor(private postService: PostService, private router: Router) {}
ngOnInit(): void {
this.postService.getPosts().subscribe(posts => {
this.post = posts.post;
},
err => {
console.log(err);
return false;
});
}
}
我的博客页面组件 HTML:
<app-header></app-header>
<div fxLayout="row wrap" fxLayoutAlign="center">
<mat-card *ngIf="post" class="card">
<mat-card-header>
<mat-card-title class="title">{{post.postTitle}}</mat-card-title>
<mat-card-subtitle class="subtitle">Author: {{post.postAuthor}}</mat-card-subtitle>
<mat-card-subtitle class="subtitle">Content: {{post.postContent}}</mat-card-subtitle>
</mat-card-header>
<mat-card-actions class="multi-button">
<button mat-icon-button><span class="fa fa-share fa-lg"></span></button>
<button mat-icon-button><span class="fa fa-trash fa-lg"></span></button>
<!-- <button mat-icon-button><span class="fa fa-heart fa-lg"></span></button> -->
</mat-card-actions>
</mat-card>
</div>
<app-footer></app-footer>
控制台或浏览器中没有错误。该博客只是不提交并给出了我编入其中的错误消息。我一直无法弄清楚问题所在。我已经测试了我在输入和ckeditor中输入的数据是否出现在mat-card模块中并且工作正常。请有人告诉我我在这里做错了什么。谢谢!
由于您调用的端点没有 return .success
属性,因此您无法使用它来确定调用是否成功。
响应中是否有任何其他数据表明它是否成功?
如果不是,也许您可以假设非错误响应是成功的,并在错误处理程序中捕获错误:
onBlogSubmit() {
const post = {
postTitle: this.postTitle,
postAuthor: this.postAuthor,
postContent: this.postContent,
postImgUrl: this.postImgUrl
}
this.postService.addPost(post).subscribe(
data => {
this.postService.getPosts();
this.flashMessage.show('Blog Submitted Successfully', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/blog-page']);
},
error => {
this.flashMessage.show('Something Went Wrong', {cssClass: 'alert-danger', timeout: 3000});
}
);
}
你的blog-page
有问题。
更正:
HTML:
<app-header></app-header>
<div *ngFor="let post of posts" fxLayout="row wrap" fxLayoutAlign="center">
<mat-card class="card">
<mat-card-header>
<mat-card-title class="title">{{post.postTitle}}</mat-card-title>
<mat-card-subtitle class="subtitle">Author: {{post.postAuthor}}</mat-card-subtitle>
<mat-card-subtitle class="subtitle">Content: {{post.postContent}}</mat-card-subtitle>
</mat-card-header>
<mat-card-actions class="multi-button">
<button mat-icon-button><span class="fa fa-share fa-lg"></span></button>
<button mat-icon-button><span class="fa fa-trash fa-lg"></span></button>
<!-- <button mat-icon-button><span class="fa fa-heart fa-lg"></span></button> -->
</mat-card-actions>
</mat-card>
</div>
TypeScript:
import { Component, OnInit } from "@angular/core";
import { PostService } from "../post.service";
import { Router } from "@angular/router";
@Component({
selector: "app-blog-page",
templateUrl: "./blog-page.component.html"
styleUrls: ["./blog-page.component.scss"]
})
export class BlogPageComponent implements OnInit {
posts: Object;
constructor(private postService: PostService, private router: Router) {}
ngOnInit(): void {
this.postService.getPosts().subscribe(
posts => {
console.log(posts);
this.posts = posts;
},
err => {
console.log(err);
return false;
}
);
}
}
在 StackBlitz 进行演示。
注意:我评论了你的一些组件并嘲笑了你的API。请用你真实的API来测试
编辑:
同时更改blog-add
组件的HTML:
<app-header></app-header>
<div class="row" *ngIf="post">
<div class="col-sm-12 form-main">
<form name="postForm" (ngsubmit)="onBlogSubmit()" class="text-center border border-light p-5 shadow-lg">
<input type="text" class="form-control mb-4" placeholder="Name" [(ngModel)]="postTitle" name="postTitle">
<input type="text" class="form-control mb-4" placeholder="Username" [(ngModel)]="postAuthor" name="postAuthor">
<img ng-src="postImgUrl">
<ckeditor matCkeditor class="form-control mb-8" [(ngModel)]="postContent" name="postContent"></ckeditor>
<button mat-raised-button type="submit" class="btn btn-success btn-block get" (click)="onBlogSubmit()">Submit</button>
</form>
</div>
</div>