成功调用api后手动刷新组件

时间:2019-05-16 20:55:50

标签: angular api page-refresh

因此,我编写了自己的api,并且进行了大量的api调用。问题是调用结束后我的组件不会更新。我一直在做一些研究,这是我想出的:

  onSubmit() {
    if (this._user) {
      this._commentDataService
        .postComment(
          this.imageId,
          new Comment(
            this.loggedInUser.firstName + ' ' + this.loggedInUser.lastName,
            this.messageForm.value.message,
            new Date(),
            this.imageId,
            this.loggedInUser.id
          )
        )
        .subscribe(com => {
          console.log(com);
          this._changeDetectorRef.markForCheck();
        });
    } else {
      this.openSnackBar('You need to be logged in to send a message.');
    }
  }

但显然,markForCheck()在完成发布请求后不会刷新我的组件:

  postComment(imageId: number, comment: Comment): Observable<Comment> {
    return this.http.post<Comment>(
      `${environment.apiUrl}/images/${imageId}/comments`,
      comment.toJSON()
    );
  }

对于PUT和DELETE(我还没有测试过的那些东西),我也需要这样做。

能请你帮我吗?

问题的下一部分(现在我的组件刷新了:)) 因此,当我在评论上发布/放置评论时,它绝对好用,但是当我尝试删除帖子时,它会删除数据库中正确的帖子,但会在视觉上删除要删除的评论下方的评论。当我刷新时,正确的注释将被视觉删除,而被视觉删除的注释又回到了原处。我不知道为什么要这样做(也许这与注释顺序有时会改变的事实有关(我不知道它们在什么条件下会改变,或者为什么会这样) 代码:

DeleteCommentComponent:

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MatSnackBar, MAT_DIALOG_DATA } from '@angular/material';
import { CommentDataService } from '../comment-data.service';

@Component({
  selector: 'app-delete-comment',
  templateUrl: './delete-comment.component.html',
  styleUrls: ['./delete-comment.component.css']
})
export class DeleteCommentComponent implements OnInit {
  constructor(
    public dialogRef: MatDialogRef<DeleteCommentComponent>,
    private _commentDataService: CommentDataService,
    private _snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {}

  ngOnInit() {}

  cancel() {
    this.openSnackbar('Comment did not get deleted.');
    this.onNoClick();
  }

  delete() {
    this._commentDataService
      .deleteComment(this.data.comment.myImageId, this.data.comment.id)
      .subscribe(c => {
        console.log(c);
        if (c) {
          this.data.array.pop(c);
          this.openSnackbar('Comment succesfully deleted.');
        } else {
          this.openSnackbar(
            'Something went wrong deleting the comment, please try again.'
          );
        }
      });
    this.onNoClick();
  }

  private onNoClick(): void {
    this.dialogRef.close();
  }

  private openSnackbar(message: string) {
    this._snackBar.open(message, 'Close', { duration: 2000 });
  }
}
<h2 mat-dialog-title>Delete a comment</h2>
<mat-dialog-content>
  Are you sure you want to delete this comment?
</mat-dialog-content>
<mat-dialog-actions>
  <button mat-raised-button class="noBtn right" (click)="cancel()">No</button>
  <button mat-raised-button class="yesBtn" (click)="delete()">Yes</button>
</mat-dialog-actions>

打开此对话框的方法:

  openDeleteDialog(comment: Comment) {
    const dialogRef = this.dialog.open(DeleteCommentComponent, {
      width: '300px',
      height: '200px',
      data: { comment, array: this.comments }
    });
  }

当您单击删除按钮时,将调用此名称:

<div class="overflow">
  <div
    fxLayout="row"
    fxLayoutAlign="space-between"
    *ngFor="let comment of comments"
  >
    <div>
      <div class="commentDiv" data-cy="comments">
        <span class="user left">{{ comment.author }}: </span>
        <span>{{ comment.content }}</span>
      </div>
      <div class="iconDiv right" *ngIf="isAuthor(comment)">
        <mat-icon class="edit" (click)="openChangeDialog(comment)"
          >edit</mat-icon
        ><mat-icon class="delete" (click)="openDeleteDialog(comment)"
          >delete</mat-icon
        >
      </div>
    </div>
  </div>
</div>
<form [formGroup]="messageForm" (ngSubmit)="onSubmit()" data-cy="commentForm">
  <mat-form-field>
    <input
      matInput
      aria-label="Message"
      placeholder="Message"
      type="text"
      class="browser-default"
      formControlName="message"
    />
    <mat-error
      *ngIf="
        messageForm.get('message')['errors'] &&
        messageForm.get('message').touched
      "
    >
      {{ getErrorMessage(messageForm.get('message')['errors']) }}
    </mat-error>
  </mat-form-field>

  <button mat-raised-button type="submit" [disabled]="!messageForm.valid">
    <mat-icon>send</mat-icon>
  </button>
</form>

1 个答案:

答案 0 :(得分:0)

API调用完成后,您应该使用异步管道来应用新更改

来自文档

  

AsyncPipe订阅一个observable或promise,并返回   它发出的最新值。发出新值时,管道   标记要检查更改的组件。

示例

@Component({
  selector: 'async-observable-pipe',
  template: `<div><code>observable|async</code>:
       Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
  time = new Observable(observer =>
    setInterval(() => observer.next(new Date().toString()), 1000)
  );
}

可以找到更多here