将数组推入数组中,并在更新数组后将其保存到数据库-angular

时间:2018-10-24 16:11:34

标签: angular typescript

当用户使用onSubmit()提交注释并使用updateCabin更新小屋时,我想将数组注释推入cab.comments数组,并在其中添加新注释的小屋数组更新之后。 在控制台中运行“ ng serve --open”时,出现错误:

错误TS1128:需要声明或声明

我正在主文件夹中使用JSON数据库。
我真的很陌生,迷路了。

这是我的组件

            import { Location } from '@angular/common';
    import { Component, Inject, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { Params, ActivatedRoute } from '@angular/router';


    import { Comment } from '../shared/comment';
    import { Cabin } from '../shared/cabin';
    import { CabinService } from '../services/cabin.service';

    @Component({
      selector: 'app-cabin-detail',
      templateUrl: './cabin-detail.component.html',
      styleUrls: ['./cabin-detail.component.css']
    })
    export class CabinDetailComponent implements OnInit {
       cabin: Cabin;
       cabins: Cabin[];
      comment: Comment;
      commentForm: FormGroup;
      errMess: string;


      formErrors = {
        'author' : '',
        'rating' : '',
        'comment' : ''
      };

      validationMessages = {
        'author' : {
          'required' : 'Name is required',
          'minlength' : 'Name must be at least 2 characters long',
          'maxlength' : 'Name cannot be more that 25 characters long'
        }
      };


      constructor(
        private cabinService: CabinService,
         private fb: FormBuilder,
        private location: Location,
        private route: ActivatedRoute,
        @Inject("BaseURL") private BaseURL
      ) {
        this.createForm();
      }

      ngOnInit(): void {
        this.getCabin();
        this.getCabins();


      }

      getCabin(): void {
        const id = +this.route.snapshot.paramMap.get('id');
        this.cabinService.getCabin(id)
          .subscribe(cabin => this.cabin = cabin);
      }


      getCabins(): void {
        this.cabinService.getCabins()
        .subscribe(cabins => this.cabins = cabins);
      }

    /* addComment(description: string): void {
        description = description.trim();
        if (!description) { return; }
        this.cabinService.addCabin({ description } as Cabin)
          .subscribe(cabin => {
            this.cabins.push(cabin);
          });
      }
     */
     /* delete(cabin: Cabin): void {
        this.cabins = this.cabins.filter(h => h !== cabin);
        this.cabinService.deleteCabin(cabin).subscribe();
      }
      */

        createForm() {
        this.commentForm = this.fb.group({
          author: ['', [ Validators.required, Validators.minLength(2) ] ],
          rating: 5,
          comment: ['', [ Validators.required ] ],
        });

        this.commentForm.valueChanges
          .subscribe(data => this.onValueChanged(data));

        this.onValueChanged(); // (re)set form validation messages
      }

        onValueChanged(commentFormData?: any) {
        if (!this.commentForm) {
          return;
        }
        const form = this.commentForm;
        for (const field in this.formErrors) {
          this.formErrors[field] = '';
          const control = form.get(field);
          if (control && control.dirty && !control.valid) {
            const messages = this.validationMessages[field];
            for (const key in control.errors) {
              this.formErrors[field] += messages[key] + ' ';
            }
          }
        }

        if (this.commentForm.valid) {
          this.comment = this.commentForm.value;
        } else {
          this.comment = undefined;
        }
      }

      onSubmit(cabinId) {
        const id = +this.route.snapshot.paramMap.get('id');
        console.log(cabinId)

        this.cabin.comments.push(this.comment);
        this.cabinService.updatePosts(cabinId);

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


    }

我的cabService

            import { Injectable } from '@angular/core';

    import { HttpClient, HttpHeaders } from '@angular/common/http';

    import { Observable, of } from 'rxjs';
    import { catchError, map, tap } from 'rxjs/operators';

    import { Cabin } from '../shared/cabin';
    import { MessageService } from './message.service';



    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };

    @Injectable({
      providedIn: 'root'
    })
    export class CabinService {

      private cabinsUrl = 'http://localhost:3000/cabins';  // URL to web api

      constructor(
        private http: HttpClient,
        private messageService: MessageService) { }

      /** GET cabins from the server */
      getCabins(): Observable<Cabin[]> {
        return this.http.get<Cabin[]>(this.cabinsUrl)
          .pipe(
            tap(cabins => this.log('fetched cabins')),
            catchError(this.handleError('getCabins', []))
          );
      }

      getFeaturedCabin(): Observable<Cabin[]> {
        const url = 'http://localhost:3000/cabins?featured=true';
        return this.http.get<Cabin[]>(url).pipe(
          tap(_ => this.log('o')),
          catchError(this.handleError<Cabin[]>(`getFeaturedCabin`))
        );
      }
      /** GET cabin by id. Return `undefined` when id not found */
      getCabinNo404<Data>(id: number): Observable<Cabin> {
        const url = `${this.cabinsUrl}/?id=${id}`;
        return this.http.get<Cabin[]>(url)
          .pipe(
            map(cabins => cabins[0]), // returns a {0|1} element array
            tap(h => {
              const outcome = h ? `fetched` : `did not find`;
              this.log(`${outcome} cabin id=${id}`);
            }),
            catchError(this.handleError<Cabin>(`getCabin id=${id}`))
          );
      }

      /** GET cabin by id. Will 404 if id not found */
      getCabin(id: number): Observable<Cabin> {
        const url = `${this.cabinsUrl}/${id}`;
        return this.http.get<Cabin>(url).pipe(
          tap(_ => this.log(`fetched cabin id=${id}`)),
          catchError(this.handleError<Cabin>(`getCabin id=${id}`))
        );
      }

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


            return {
              description: cabin.description,
              featured: cabin.featured,
              comments: cabin.comments

            };


          })
        ).subscribe(updatedEntries => {
          console.log(updatedEntries);

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

        });

      }



      /*



      /**
       * Handle Http operation that failed.
       * Let the app continue.
       * @param operation - name of the operation that failed
       * @param result - optional value to return as the observable result
       */
      private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {

          // TODO: send the error to remote logging infrastructure
          console.error(error); // log to console instead

          // TODO: better job of transforming error for user consumption
          this.log(`${operation} failed: ${error.message}`);

          // Let the app keep running by returning an empty result.
          return of(result as T);
        };
      }

      /** Log a CabinService message with the MessageService */
      private log(message: string) {
        this.messageService.add(`CabinService: ${message}`);
      }

    }

我的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"
            }
          ]
        }
      ]

1 个答案:

答案 0 :(得分:0)

问题是put方法本身,您需要放回整个对象..我想做的是先获取对象,然后添加数据,并将其全部推回原位(如果您使用mongoose进行操作)例如,您只能更新架构的子架构,但这取决于db引擎。

updatePosts(){
 const data={"last": "test2"};

 return this.http.get<{post: Posts}>('http://localhost:3000/posts/5').pipe(
  map(post=>{
    console.log(post);


     return{
           description: cabin.description,
           featured: cabin.featured,
           comments: cabin.comments

         };


     })
    ).subscribe(updatedEntries=>{
      updatedEntries.cabin.comments.push(data);
      return this.http.put('http://localhost:3000/cabins/'+id, updatedEntries);



});