JSON服务器中的空数组未收到初始值

时间:2019-07-13 10:27:37

标签: javascript angular

如果至少有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时// //让maxIndex = article.length-1; 因为article.length为零,则maxIndex = -1。 我已经尝试了很多方法来重写代码而没有成功

2 个答案:

答案 0 :(得分:0)

检查代码开头的数组是否为空。

// Generate article id then create article
this.articleService.getAllArticles()
  .subscribe(articles => {

    // Generate article id
    if (!articles.length) {

        article.id = 1;

    } else {

        article.id = articles[articles.length - 1].id + 1;
    }

    // Create article
    this.articleService.createArticle(article)
      .subscribe(successCode => {
        this.statusCode = successCode;
        this.getAllArticles();
        this.backToCreateArticle();
      },
        errorCode => this.statusCode = errorCode
      );
});

答案 1 :(得分:0)

我的代码无法正常工作,因为我使用的是零而不是null:(

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

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