Данные отображаются только после обновления - PullRequest
0 голосов
/ 26 июня 2018

Я создаю раздел комментариев в моем приложении, когда пользователь вводит комментарии и отправляет, комментарий должен немедленно отображаться в интерфейсе, к сожалению, теперь комментарии видны только после обновления,

Вот что у меня есть:

Отображение комментариев

component.ts

  ngOnInit() {
       this.activeRouter.params.subscribe((params) => {
      // tslint:disable-next-line:prefer-const
      let id = params['id'];
      this.moviesService.getComments(id)
        .subscribe(comments => {
          console.log(comments);
          this.comments = comments;
        });
    });
}

service.ts

 getComments(id: string): Observable<any> {
    const url = `${apiUrl + this.commentsUrl}/${id}`;
    return this.http.get(url, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }

HTML

<div *ngFor="let comment of comments" class="col-md-7">
          <ul class="list-group">
            <li class="list-group-item">Author: {{comment.author}}</li>
            <li class="list-group-item">Comments: {{comment.description}}</li>
          </ul>
          <br>
        </div>

**

Добавление комментариев:

** service.ts

  // Adds comments
      addReview(author, description) {
        const uri = 'http://localhost:8000/movies/comments';
        const obj = {
          author: author,
          description: description
        };
        return this.http.post(uri, obj);
      }

compo.ts

  createForm() {
    this.angForm = this.fb.group({
      author: ['', Validators.required],
      description: ['', Validators.required]
    });
  }
  addReview(author, description) {
    this.moviesService.addReview(author, description).subscribe(success => {
      this.flashMessages.show('You are data we succesfully submitted', { cssClass: 'alert-success', timeout: 3000 });
    }, error => {
      this.flashMessages.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
    });
  }

HTML

<div class="col-md-7 movie-form" >
          <flash-messages></flash-messages>
          <form [formGroup]="angForm" novalidate>
            <div class="form-group">
              <label class="col-md-4">Author</label>
              <input type="text" class="form-control" name="author" formControlName="author" #author />
            </div>
            <div *ngIf="angForm.controls['author'].invalid && (angForm.controls['author'].dirty || angForm.controls['author'].touched)"
              class="alert alert-danger">
              <div *ngIf="angForm.controls['author'].errors.required">
                Name is required.
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4">Description</label>
              <textarea cols="10" rows="10" type="text" class="form-control" formControlName="description" #description>
                </textarea>
            </div>
            <div *ngIf="angForm.controls['description'].invalid && (angForm.controls['description'].dirty || angForm.controls['description'].touched)"
              class="alert alert-danger">
              <div *ngIf="angForm.controls['description'].errors.required">
                description is required.
              </div>
            </div>
            <div class="form-group">
              <button (click)="addReview(author.value, description.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
            </div>
          </form>
        </div>

Вопрос

что такое wrog с моим кодом?Любое предложение помощи будет оценено

Ответы [ 2 ]

0 голосов
/ 26 июня 2018

@ Kaczkapojebana.Когда мы подписываемся на получение, НЕ означает, что в представлении было отображено изменение базы данных.(только скажите, что когда асинхронный вызов завершен, данные отображаются).Я обычно называю подписку «получить» как «подписку только одного использования».

Вы должны вручную добавить в this.comments новые данные.где?Функция подписки IN:

addReview(author, description) { 
    this.moviesService.addReview(author, description).subscribe(success => {  
      /***add manually to this.comments***********/
      this.comments.push({author:author,descripcion:description});

      this.flashMessages.show('You are data we succesfully submitted', { cssClass: 'alert-success', timeout: 3000 });
    }, error => {
      this.flashMessages.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
    });
  }

ПРИМЕЧАНИЕ. Вы также можете снова подписаться, чтобы получить все данные или, чтобы addReview ответил на все данные.комментарии »массив вручную

0 голосов
/ 26 июня 2018

Вы должны вызвать свой метод getComments при ответе на ваши комментарии.Ваш код имеет только вызов "get" в методе ngOnInit компонента.Поэтому, когда вы обновляете представление, ngOnInit выполняется снова и, таким образом, вызывается getComments.

Вы должны сделать вызов get в обратном вызове метода отправки комментариев.

EDIT# 1:

addReview(author, description) {
    this.moviesService.addReview(author, description).subscribe(success => {
        this.flashMessages.show('You are data we succesfully submitted', { cssClass: 'alert-success', timeout: 3000 });
        // get the id
        this.moviesService.getComments(id).subscribe(comments => {
            console.log(comments);
            this.comments = comments;
        });
    }, error => {
        this.flashMessages.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...