【发布时间】:2019-04-01 00:56:18
【问题描述】:
我有允许用户提交 cmets 的 textarea,我想获取提交评论的时间,并与添加的评论一起保存到 json。
不幸的是,当我提交评论时,评论和日期按预期显示,但是当我刷新页面时,日期不见了。
注意我使用的是json-server
在 json 文件中提交评论后,我想要这样的东西:
"comment": [
{
"id": 1,
"localTime": "2018-10-27T13:42:55",
"description": "Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et lig\n"
}
]
问题:现在提交评论时,我在 json 服务器中有以下内容,
"comment": [
{
"id": 1,
"localTime": null,
"description": "Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et lig\n"
}
]
这是我迄今为止尝试从输入的评论中获取日期的方法。
HTML:
<form class="add-comments" [formGroup]="addForm" (keyup.enter)="addComments()">
<input type="hidden" id="localTime" name="localTime">
<div class="form-group">
<textarea class="form-control" rows="1" placeholder="Add comments" formControlName="description" id="description"></textarea>
</div>
</form>
这是关于组件 ts 的方法。
addComments(task_id) {
const formData = this.addForm.value;
formData.task_id = task_id;
this.userService.addComments(formData)
.subscribe(data => {
this.comments.push(this.addForm.value);
});
const date = new Date();
const d = date.getUTCDate();
const day = (d < 10) ? '0' + d : d;
const m = date.getUTCMonth() + 1;
const month = (m < 10) ? '0' + m : m;
const year = date.getUTCFullYear();
const h = date.getUTCHours();
const hour = (h < 10) ? '0' + h : h;
const mi = date.getUTCMinutes();
const minute = (mi < 10) ? '0' + mi : mi;
const sc = date.getUTCSeconds();
const second = (sc < 10) ? '0' + sc : sc;
const loctime = `${year}-${month}-${day}T${hour}:${minute}:${second}`;
this. addForm.get('localTime').setValue(loctime);
}
这里是添加 cmets 到服务器的服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Status } from '../model/statuses.model';
import { Comment } from '../model/comments.model';
import { User } from '../model/user.model';
@Injectable({
providedIn: 'root'
})
export class UserService {
status: Status[];
constructor(private http: HttpClient) { }
statusUrl = 'http://localhost:3000/statuses';
commentsUrl = 'http://localhost:3000/comment';
usersUrl = 'http://localhost:3000/users';
addComments(comments: Comment) {
return this.http.post(this.commentsUrl, comments);
}
getComments(id: number) {
return this.http.get<Comment[]>(this.commentsUrl);
}
}
这是类模型
export class Comment {
id: number;
username: string;
email: string;
days: number;
localTime: Date;
description: string;
}
我需要改变什么才能得到我想要的??
【问题讨论】:
-
您的数据将在刷新时被清除。您可以尝试使用
localStorage或sessionStorage来达到您的目的。 -
为什么在使用 json 服务器时进行会话存储????
-
呃,你为什么相信 client 会向你的 server 发送正确的日期?
-
@Stavm 是我的 qn 还是 @sarthank?
标签: javascript angular html typescript angular6