javascript - json-server 中的空数组未接收到初始值
问题描述
如果至少 1 个对象已经存在,则不会填充 json 文件中的空数组
在 CRUD 项目中使用 json-server 和 Angular 7 的技术
//Generate article id then create article
this.articleService.getAllArticles()
.subscribe(articles => {
//Generate article id
let maxIndex = articles.length - 1;
let articleWithMaxIndex = articles[maxIndex];
let articleId = articleWithMaxIndex.id + 1;
article.id = articleId;
//Create article
this.articleService.createArticle(article)
.subscribe(successCode => {
this.statusCode = successCode;
this.getAllArticles();
this.backToCreateArticle();
},
errorCode => this.statusCode = errorCode
);
});
问题似乎是 maxIndex 为 -1 时的情况 // let maxIndex =articles.length - 1; 因为 article.length 为零,所以 maxIndex = -1。我尝试了很多方法来重写代码但没有成功
解决方案
我的代码不起作用,因为我使用零而不是 null :(
if (this.maxIndex == 0) {
this.articleId = 1;
} else {
let articleWithMaxIndex = articles[this.maxIndex];
let articleId = articleWithMaxIndex.id + 1;
article.id = articleId;
推荐阅读
- powershell - 另一个具有相同属性 identifierUris 值的对象已经存在
- node.js - 是否有必要验证加密的密码服务器端?
- angular - Angular 5 'Content-Type':'multipart/form-data' 被重置为 'application/json'
- python - 在张量流中找到二维张量分组的平均值?
- python - OrientDB:在 pyorient 中为两个顶点类创建边
- python - 仅在第一个脚本完成后执行第二个 python 脚本
- github-pages - 将 Hugo 加载到 GitHub 页面
- c# - unityplayer 中的地形纹理模糊
- php - 在 codeigniter PHP 中使用数组检查索引键
- math - 16bit product throughoutput可以在没有具体说明的情况下翻倍吗?