首页 > 解决方案 > 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。我尝试了很多方法来重写代码但没有成功

标签: javascriptangular

解决方案


我的代码不起作用,因为我使用零而不是 null :(

if (this.maxIndex == 0) {
           this.articleId = 1;

} else {
  let articleWithMaxIndex = articles[this.maxIndex];
  let articleId = articleWithMaxIndex.id + 1;
  article.id = articleId;

推荐阅读