简体   繁体   English

从 Angular 中的 http 请求更新数据

[英]Updating data from http request in Angular

I've got an interface that basically lets you add, edit, or delete a user.我有一个界面,基本上可以让您添加、编辑或删除用户。 When the component initializes it does an http request to the server to get current users.当组件初始化时,它会向服务器发出 http 请求以获取当前用户。 So if you go to edit or delete a user there is a dropdown of all the users received from that request.因此,如果您 go 编辑或删除用户,则会出现从该请求收到的所有用户的下拉列表。 The problem is that if the I delete a user for example through http request, I need to then send another get request to update the data client side so that if you were to open the dropdown again it would reflect the changes made.问题是,如果我删除了一个用户,例如通过 http 请求,我需要发送另一个获取请求来更新数据客户端,这样如果你再次打开下拉列表,它就会反映所做的更改。 I can fix this problem by running 'ngOnInit()' again after successful request but this means I'm 'subscribing' every time the user does something..我可以通过在成功请求后再次运行“ngOnInit()”来解决这个问题,但这意味着每次用户做某事时我都在“订阅”。

ngOnInit() {
   this.service.getUsers()
   .subscribe(payload => {
      payload.forEach(user => {
         this.users.push(user);
      });
   });
} 

I'm new to Angular so I'm not entirely sure the best way to go about it but I feel like running this method of 'subscribing' every time the user performs a request is wrong.我是 Angular 的新手,所以我不完全确定 go 的最佳方法,但我觉得每次用户执行请求时都运行这种“订阅”方法是错误的。 Any help would be appreciated.任何帮助,将不胜感激。

Ideally It's best if you request the data from the server once you have performed a POST/Delete operation just to be sure that you get the latest/correct data from the server.理想情况下,最好在执行 POST/Delete 操作后从服务器请求数据,以确保从服务器获得最新/正确的数据。 So Yes, it is OK to get data again after delete.所以是的,删除后再次获取数据是可以的。

I have give the code sample below of typically how you can do it.我在下面给出了典型的代码示例,您可以如何做到这一点。 Don't forget to unsubscribe the observables and dispose of them later.不要忘记取消订阅 observables 并在以后处理它们。

private subscriptions = new Subscription();

ngOnInit() {
  this.refreshList()
}

deleteUser(id: string) {
        this.subscriptions.add(
            this.service.deleteUser(id).subscribe(
                success => {
                    this.notificationService.showNotification(`User deleted: ${success.name}`);
                    this.refreshList();
                },
                errors => this.notificationService.showErrors('Error deleting User', errors)
            )
        );
    }

refreshList() {
this.subscriptions.add(
 this.service.getUsers()
   .subscribe(payload => {
        this.users = payload;         
   }));
}

ngOnDestroy() {
    this.subscriptions.unsubscribe();
}

All you have to do is removing the deleted user from the users array locally inside your class after you get success response from the delete request.您所要做的就是在您从删除请求中获得成功响应后,从 class 本地的users数组中删除已删除的用户。 Do not use this.ngOnInit();不要使用this.ngOnInit(); and of course don't subscribe again to the same api to get the new data.当然不要再次订阅相同的 api 来获取新数据。

Let's say that you get the id of the user you want to delete and send this id to through the delete api , you save it in a poroperty userId .假设您获得了要删除的用户的id并通过delete api将此 id 发送给,您将其保存在一个端口userId中。 Then:然后:

  1. get user index in the users array: let deletedUserIndex = this.users.findIndex(item => item.id === this.userId);users数组中获取用户索引: let deletedUserIndex = this.users.findIndex(item => item.id === this.userId);

  2. delete the user object from the users array: this.users.splice(deletedUserIndex, 1);从用户数组中删除用户 object: this.users.splice(deletedUserIndex, 1);

And that's it就是这样

Refactor out the code that requests for current users in a private method, so that you can reuse it -重构以私有方法请求当前用户的代码,以便您可以重用它 -

private loadUsers(): void {
    this.service.getUsers()
        .subscribe(payload => {
            payload.forEach(user => {
                this.users.push(user);
            });
        });
}

Then you can call that private method from inside the ngOnInit() -然后您可以从ngOnInit()内部调用该私有方法 -

ngOnInit() {
    this.loadUsers();
}

and also from inside your delete method, when the deletion is done -以及从您的删除方法内部,删除完成后 -

deleteUser(id: number): void {
    this.service.deleteUsers(id)
        .subscribe(p => {
            console.log('User deleted Successfully!');
            this.loadUsers();    // reusing loadUsers()
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM