放入angular不起作用将数组放入JSON数据库

时间:2018-10-27 16:53:17

标签: angular typescript

我想将一个数组注释推入cab.comments数组。新注释在数组中,但没有将其推送到数据库。 我没有错误

我在主文件夹中使用JSON数据库。

我真的很陌生,迷路了。

这是我的组件文件,其中onSubmit我的控制台日志中的机舱和ID在这里有效

onSubmit() {
    const id = +this.route.snapshot.paramMap.get('id');
    this.cabin.comments.push(this.comment);
    this.cabinService.updatePosts(this.cabin.id, this.comment);
    console.log(this.cabin);
    console.log(id);

    this.commentForm.reset({
        author: '',
        rating: 5,
        comment: ''
    });
}

我的cabService我的控制台日志适用于this.cabin,但不适用于updatedEntries。推杆不起作用。

 updatePosts(id, newcomment) {
const comment: Comment = newcomment;
return this.http.get<Cabin>('http://localhost:3000/cabins/' + id).pipe(
  map(cabin => {


    return {
        id: cabin.id,
        name: cabin.name,
        description: cabin.description,
        priceweek:  cabin.priceweek,
        pricemonth:  cabin.pricemonth,
        featured: cabin.featured,
        comments: cabin.comments


    };


  })
).subscribe(updatedCabin => {
  updatedCabin.comments.push(comment);

  return this.http.put('http://localhost:3000/cabins/' + id, updatedCabin);

});

}

我的JSON数据库

      "cabins": [
        {
          "id": 0,
          "description": "Tucked away on the hillside among lush gardens of banana & citrus trees",
          "featured": "true",
          "comments": [
            {
              "rating": 5,
              "comment": "Beautiful place!",
              "author": "John Gomez",
              "date": "2018-10-16T17:57:28.556094Z"
            },
            {
              "rating": 4,
              "comment": "Amazing!",
              "author": "Paul Villar",
              "date": "2017-09-05T17:57:28.556094Z"
            }
          ]
        }
      ]

这里是整个项目的堆叠闪电战的链接

https://stackblitz.com/edit/angular-uonucb?embed=1&file=src/app/services/cabin.service.ts

2 个答案:

答案 0 :(得分:0)

您在此行上缺少正斜杠:

return this.http.put('http://localhost:3000/cabins' +id, updatedEntries);

因此,您正在向http://localhost:3000/cabins1234而不是http://localhost:3000/cabins/1234发出PUT请求,并且先前的端点不存在。

答案 1 :(得分:0)

更改您的服务方法,如下所示:

  updatePosts(id, newcomment) {
    const comment: Comment = newcomment;
    return this.http.get<Cabin>('http://localhost:3000/cabins/' + id).pipe(
      map(cabin => {


        return {
          id: cabin.id,
          name: cabin.name,
          description: cabin.description,
          priceweek: cabin.priceweek,
          pricemonth: cabin.pricemonth,
          featured: cabin.featured,
          comments: cabin.comments


        };


      }),
      flatMap((updatedCabin) => {
        updatedCabin.comments.push(comment);
        return this.http.put(this.cabinsUrl + '/' + id, updatedCabin);
      })
    );

  }

然后将链接可观察对象,并允许第二个返回。然后,您将可以像这样呼叫订阅:

this.cabinService.updatePosts(this.cabin.id, this.comment).subscribe(() => {
    console.log("PUT is done");
})
相关问题