【问题标题】:The new record created is only displayed after the page is reloaded创建的新记录仅在页面重新加载后显示
【发布时间】:2018-07-03 15:31:29
【问题描述】:

我有一个带有创建新记录的表单的模态窗口。它应该是这样工作的:单击创建模式按钮后,窗口应立即关闭,新创建的记录将出现在表格中,并且右侧应出现一条消息,表明该记录已成功创建。但目前唯一能正常工作的只是关闭模态窗口,看到新记录需要刷新页面,而关于创建记录的消息根本不显示。

如何解决这个问题?

import { Component, OnInit, Input, ViewContainerRef, TemplateRef } from '@angular/core';
import { DialogRef, ModalComponent } from 'angular2-modal';
import { Post } from '../../../../../models/post.model';
import { PostService} from '../../../../../services/post/post.service';
import { BSModalContext } from 'angular2-modal/plugins/bootstrap';
import { ToastsManager } from "ng2-toastr";
import { Angular2TokenService } from "angular2-token";
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-add-post',
  templateUrl: './add-post.component.html',
  styleUrls: ['./add-post.component.css'],
  providers: [PostService]
})

export class AddPostComponent  implements OnInit, ModalComponent<any> {

  post = new Post;
  posts: Array<Post>;

  constructor(
    public dialog: DialogRef<any>,
    public authTokenService: Angular2TokenService, 
    private servPost: Post,
    public toastManager: ToastsManager,
    vcr: ViewContainerRef
  ) { 
    toastManager.setRootViewContainerRef(vcr);
  }

  ngOnInit() {
  }



savePost() {
  this.servPost.createPost(this.post).subscribe
    (success => {
        this.toastManager.success('Data successfully created!', 'Done');
        this.servPost.getPosts().subscribe(posts => {
          console.log(posts);
          this.posts = posts;
        });


    }, error => {
      this.toastManager.error(getErrorTextFromJSON(error.json()), 'Error');
    });

    this.dialog.close(null); 

 }

}

Сan 在创建新记录后以某种方式添加页面刷新选项?至少,一个人不需要自己更新页面来显示新记录。

【问题讨论】:

  • @Eliseo 没有帮助,更新了问题代码
  • 请出示您的 HTML 模板的代码。
  • 对不起,我这么快就看到了你的问题。检查 createPost 的响应(即使您可以将 this.dialog.close(null) 放入订阅函数 od getPost

标签: angular typescript


【解决方案1】:

如果 createPost 正在返回新创建的实体,那么您可以:

savePost() {
  this.servPost.createPost(this.post).subscribe(
     data => {

        this.toastManager.success('Data successfully created!', 'Done');

        // check returned data from rest service
        console.log(data);

        // add the returned data from rest service into posts array
        this.posts.push( data );

        this.dialog.close(null);

     }, 
     error => {
        this.toastManager.error(getErrorTextFromJSON(error.json()), 'Error');
     }
  );

}

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2017-10-09
    相关资源
    最近更新 更多