【问题标题】:Although I delete the data, I cannot see it being deleted unless I refresh the page虽然我删除了数据,但除非我刷新页面,否则我看不到它被删除
【发布时间】:2020-01-30 02:55:18
【问题描述】:

当我单击它时,它会添加数据,但是当我刷新页面时,我可以看到它已添加。 像这样删除是做同样的问题。我删除了,但我只能看到刷新页面时,它被删除了。我该如何解决这种情况?

app.component.ts

  constructor(private srv: UserServiceService) {}
  users: any = [];
  checkForm: any;
  name: FormControl;
  surname: FormControl;
  age: FormControl;

  async ngOnInit() {
    (this.name = new FormControl(
      "",
      Validators.compose([Validators.required])
    )),
      (this.surname = new FormControl(
        "",
        Validators.compose([Validators.required])
      )),
      (this.age = new FormControl(
        null,
        Validators.compose([Validators.required])
      ));
    this.getAllUsers();
  }

  async getAllUsers() {
    await this.srv.allUsers().subscribe(val => {
      this.users = val;
    });
  }

  addUserFunction() {
    this.srv
      .addUserService(this.name, this.surname, this.age)
      .subscribe(val => {
        console.log("val: ", val);
      });
    this.name.reset();
    this.surname.reset();
    this.age.reset();
  }

  async deleteUser(id) {
    await this.srv.deleteUserService(id).subscribe(user => {
      console.log(user); 
    });
  }

user-service.service.ts

export class UserServiceService {
  constructor(private http: HttpClient) {}

  allUsers() {
    return this.http.get("http://localhost:3000/get_users");
  }

  addUserService(name, surname, age) {
    return this.http.post("http://localhost:3000/add_user", {
      name: name,
      surname: surname,
      age: age
    });
  }

  deleteUserService(id) {
    return this.http.delete("http://localhost:3000/delete_user/" + id);
  }
}

【问题讨论】:

    标签: node.js angular mongodb mongodb-query


    【解决方案1】:

    成功删除后,如果您不想去服务器获取新的用户列表,您可以过滤您的用户,如下所示:

    this.users =  this.users.filter(function(index) {
        return this.users.id== index;
    });
    

    所以你可以把它放到订阅中的删除方法中。

    您也可以在创建时使用相同的方法,只需将新用户添加到列表中,或从服务器获取新用户。

    我建议在您的创建方法中返回添加到数据库的新用户,并将该对象放在客户端的数组中,这样您就可以在一次调用中获得来自服务器的完整对象。

    【讨论】:

      【解决方案2】:

      删除/创建用户后,再次调用组件中的 getAllUsers() 方法刷新数据。因为 ngOnInit() 只会在你的组件创建后被调用一次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-17
        • 2018-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多