行为主题自动加载而无需单击问题

发布于 2025-02-03 05:52:23 字数 5093 浏览 4 评论 0原文

首先,我遇到的奇怪问题,我尝试提交表格成功,而没有任何问题是下面的代码摘录。

userrole.ts

ngOnInit() {
    const userSubscription = this.userManagementService.currentUsersIdValue.pipe(
      switchMap((userId: string) => {
        if (userId.length > 0) {
          return this.userManagementService.getUsers(userId.toString());
        }
        else {
          return this.userDetailsArr;
        }
      }
      )).subscribe((users) => {
        if (users !== null) {
          const sbCreate = this.userManagementService.getUsersRole(users[0].id)
            .subscribe((roles: any) => {
              if (roles.length > 0) {
                this.userRoleList = roles;
                this.ref.detectChanges();
              }
            });
          this.subscriptions.push(sbCreate);
        }
      });
    this.subscriptions.push(userSubscription);
  }

    //// This is the process to submit form data
    onSubmitRole() {
        if (this.userRole.commonForm.invalid) {
          alert('Please fill the form');
          return;
        }

        const roleData = this.userRole.commonForm.value;

        ////This runs first time when I route to this page after re-routing to this page it starts again without clicking button
        const userSubscribe = this.userManagementService.currentUsersIdValue.pipe(
          switchMap((userId: string) => {
            if (userId.length > 0) {
              return this.userManagementService.getUsers(userId.toString());
            }
            else {
              return this.userDetailsArr;
            }
          }
          )).subscribe((users) => {
            if (users !== null) {
              this.authService.currentUserValue.forEach(u => {
                if (roleData.RoleID) {
                  roleData.CompanyID = roleData.CompanyID;
                  roleData.CreatedBy = roleData.CreatedBy;
                  roleData.CreatedDate = roleData.CreatedDate;
                  roleData.LastModifiedDate = new Date().toLocaleString();
                  roleData.DefaultRoleID = '00000000-0000-0000-0000-000000000000';
                }
                else {
                  roleData.RoleID = '00000000-0000-0000-0000-000000000000';
                  roleData.CompanyID = u.companyID;
                  roleData.CreatedBy = u.id;
                  roleData.CreatedDate = new Date().toLocaleString();
                  roleData.LastModifiedBy = u.id;
                  roleData.LastModifiedDate = new Date().toLocaleString();
                  roleData.Internal = true;
                  roleData.RoleTypeCode = 1;
                  roleData.DefaultRoleID = '00000000-0000-0000-0000-000000000000';
                }
    
                const sbCreate = this.userManagementService.upsertUserRole(roleData)
                  .subscribe((response: any) => {
                    if (response.Status === 200) {
                      this.router.navigate(['general-management/viewprofile']);
                    }
                    else {
                      alert(response.Description);
                    }
                  });
                this.subscriptions.push(sbCreate);
              });
            }
            else {
              if (confirm('Please edit/add any user to continue with Role!')) {
                this.router.navigate(['general-management/viewprofile']);
              }
            }
          });
        this.subscriptions.push(userSubscribe);
      }

现在问题是在页面的初始 userrole.ts 当我命中率提交此方法 onsubmitrole()时将数据交付到服务,然后将数据交付到服务器,这是可以在成功后的 mainuser.ts 页面的路由时可以 从主页到达 userrole.ts 页面,然后发生了奇怪的现象,它开始了此const userubScribe = this.usermanagementservice.currentusersidvalue.pipe insubmitrole() 此ecdiviourSubject最初将首次启动,但是在第二次编辑返回此页面后,它将自动重新启动const userubScribe = this.usermanagementservice.currentusersidvalue.pipe.pipe而无需打击 onsubmitrole()onsubmitrole()()
该过程如下 - mainuser.ts (可以对列表进行编辑以进行路由到下一页) - > userrole.ts (具有表单提交按钮,这是奇怪的问题正在发生)自动在编辑时第二次运行服务。

这是 userrole.html page

<div *ngIf="!showRolesTable">
  <form [formGroup]="userRole.commonForm" (ngSubmit)="onSubmitRole()">
    <div class="form-group">
      <label for="RoleName">Role Name</label>
      <input type="hidden" [(ngModel)]="userRole.RoleID" formControlName="RoleID">
      <input type="text" [(ngModel)]="userRole.RoleName" formControlName="RoleName" id="RoleName" placeholder="Enter Role Name">          
    </div>
    <div class="form-group">
      <label for="Description">Description</label>
      <input type="text" [(ngModel)]="userRole.Description" formControlName="Description" class="form-control"
        id="Description" placeholder="Enter Description">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>

There is strange issue I'm encountering at first I try to submit form it succeeds without any issue here is an code excerpt below from page.

userRole.ts:

ngOnInit() {
    const userSubscription = this.userManagementService.currentUsersIdValue.pipe(
      switchMap((userId: string) => {
        if (userId.length > 0) {
          return this.userManagementService.getUsers(userId.toString());
        }
        else {
          return this.userDetailsArr;
        }
      }
      )).subscribe((users) => {
        if (users !== null) {
          const sbCreate = this.userManagementService.getUsersRole(users[0].id)
            .subscribe((roles: any) => {
              if (roles.length > 0) {
                this.userRoleList = roles;
                this.ref.detectChanges();
              }
            });
          this.subscriptions.push(sbCreate);
        }
      });
    this.subscriptions.push(userSubscription);
  }

    //// This is the process to submit form data
    onSubmitRole() {
        if (this.userRole.commonForm.invalid) {
          alert('Please fill the form');
          return;
        }

        const roleData = this.userRole.commonForm.value;

        ////This runs first time when I route to this page after re-routing to this page it starts again without clicking button
        const userSubscribe = this.userManagementService.currentUsersIdValue.pipe(
          switchMap((userId: string) => {
            if (userId.length > 0) {
              return this.userManagementService.getUsers(userId.toString());
            }
            else {
              return this.userDetailsArr;
            }
          }
          )).subscribe((users) => {
            if (users !== null) {
              this.authService.currentUserValue.forEach(u => {
                if (roleData.RoleID) {
                  roleData.CompanyID = roleData.CompanyID;
                  roleData.CreatedBy = roleData.CreatedBy;
                  roleData.CreatedDate = roleData.CreatedDate;
                  roleData.LastModifiedDate = new Date().toLocaleString();
                  roleData.DefaultRoleID = '00000000-0000-0000-0000-000000000000';
                }
                else {
                  roleData.RoleID = '00000000-0000-0000-0000-000000000000';
                  roleData.CompanyID = u.companyID;
                  roleData.CreatedBy = u.id;
                  roleData.CreatedDate = new Date().toLocaleString();
                  roleData.LastModifiedBy = u.id;
                  roleData.LastModifiedDate = new Date().toLocaleString();
                  roleData.Internal = true;
                  roleData.RoleTypeCode = 1;
                  roleData.DefaultRoleID = '00000000-0000-0000-0000-000000000000';
                }
    
                const sbCreate = this.userManagementService.upsertUserRole(roleData)
                  .subscribe((response: any) => {
                    if (response.Status === 200) {
                      this.router.navigate(['general-management/viewprofile']);
                    }
                    else {
                      alert(response.Description);
                    }
                  });
                this.subscriptions.push(sbCreate);
              });
            }
            else {
              if (confirm('Please edit/add any user to continue with Role!')) {
                this.router.navigate(['general-management/viewprofile']);
              }
            }
          });
        this.subscriptions.push(userSubscribe);
      }

Now the problem is that at initial of the page userRole.ts when I hit submit to call this method onSubmitRole() it delivers the data to service and then to server, which is OK after success it routes back to mainUser.ts page when I edit a certain list
from the main page to reach userRole.ts page then the strange phenomenon happens, it starts this const userSubscribe = this.userManagementService.currentUsersIdValue.pipe from onSubmitRole() this BehaviourSubject will initially start first time but after edit second time back to this page it will automatically start again const userSubscribe = this.userManagementService.currentUsersIdValue.pipe without hitting onSubmitRole().
The process is as follow - mainUser.ts (have list which can be edited to route to next page) --> userRole.ts (which has a form submit button and here is the strange issue is happening) automatically it runs the service second time on edit.

Here is the userRole.Html page

<div *ngIf="!showRolesTable">
  <form [formGroup]="userRole.commonForm" (ngSubmit)="onSubmitRole()">
    <div class="form-group">
      <label for="RoleName">Role Name</label>
      <input type="hidden" [(ngModel)]="userRole.RoleID" formControlName="RoleID">
      <input type="text" [(ngModel)]="userRole.RoleName" formControlName="RoleName" id="RoleName" placeholder="Enter Role Name">          
    </div>
    <div class="form-group">
      <label for="Description">Description</label>
      <input type="text" [(ngModel)]="userRole.Description" formControlName="Description" class="form-control"
        id="Description" placeholder="Enter Description">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请确保从订阅中退订。实现组件中的接口,然后调用subscription.unsubscribe()。此外,如果您不需要可观察的中的先前值,那么最好使用objection()而不是capary> caparioUrSubject()在rxjs中的不同类型的主题中阅读更多信息

Be sure to unsubscribe from your subscription. Implement OnDestroy() interface in your component then call the subscription.unsubscribe(). Additionally, If you do not need the previous value in your Observable then it is better to use Subject() not BehaviourSubject(). Read more on the different types of Subjects in RxJs

痴情换悲伤 2025-02-10 05:52:24

JS中没有魔术 - 如果没有人调用onsubmitrole()(您放入了调试器语句中,它没有触发),则意味着先前的订阅仍然处于活动状态。

当您进行const userubScribe = this.usermanagementservice.currentusersidvalue.pipe(...)。订阅(...)您正在创建订阅,该订阅将继续聆听更改code> Chode> CurrentUserSidvalue 。唯一的可能性是,当您第二次转到userrole页面时,可观察到的东西会发出某些东西,并导致 userrole上一个实例触发任何东西那个管道触发。

至于解决方案... 1)确保当用户离开userrole页面时,您正在清理订阅,这实际上可能是泄漏。 2)在管道开头添加取(1)操作员:一旦收到1个值,该操作员将自动取消订阅。

There's no magic in JS - if no one is calling onSubmitRole() (you put in a debugger statement and it doesn't trigger), then it means that the previous subscription is still active.

When you do const userSubscribe = this.userManagementService.currentUsersIdValue.pipe(...).subscribe(...) you are creating a subscription which will keep listening for changes in currentUsersIdValue. The only possibility is that when you go to userRole page the second time, that observable emits something and causes the previous instance of userRole to trigger whatever that pipe triggers.

As for solutions... 1) Make sure that you're cleaning out the subscriptions when the user leaves the userRole page, that could actually be a leak. 2) add a take(1) operator at the very beginning of the pipe: This operator will automatically unsubscribe once 1 value has been received.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文