NGRX/RXJS 观察者不在页面刷新时发射

NGRX/RXJS observer not emitting on page refresh

我有一个允许用户编辑条目的组件。如果用户从前一个组件 (table) 到达编辑页面,我的观察者能够 select 来自商店的用户并使用正确的数据填充字段。

但是,如果我刷新页面,观察者会一直返回 null。奇怪的是编辑表单上的 nGif 填写了来自用户的正确标签。这告诉我 Observable 对象不为空,因为 nGif 不会呈现标签。订阅它的观察者似乎有问题。

表格:

<form id="editContainer" [formGroup]="editForm" *ngIf="userObjectUnderEdit | async as userEdit">
        <div class="form-group">
            <mat-form-field appearance="standard">
            <mat-label>{{userEdit.name}}</mat-label>
            <input class="formInput" matInput placeholder="{{userEdit.name}}" formControlName="name" required>
            </mat-form-field>
        </div>
        <div class="form-group">
            <mat-form-field appearance="standard">
                <mat-label>{{userEdit.email}}</mat-label>
                <input class="formInput" resizeToFitContent="true" matInput placeholder="{{userEdit.email}}" formControlName="email" required>
              </mat-form-field>
        </div>
...

组件:

ngOnInit() {
    console.log('in ngoninit');
    this.editBuildForm();
    this.loaduserForEdit();
    
    // this.setEditFormValues();
  }

  loadUserForEdit() {
    const routeSubscription = this.store.select(getCurrentRouteState).pipe(take(1)).subscribe(route => {
        const userId = route.params.userId;
        console.log("route params id: ", userId);
        this.store.dispatch(loadEditeduser({userId}));
        this.store.dispatch(setEditeduserId({userId}));
    });
    this.userObjectUnderEdit = this.store.select(getCurrentuser);
    const userFillSubscriber = this.userObjectUnderEdit.subscribe(user => this.userFormFill = user);
    this.setEditFormValues(this.userFormFill);
    userFillSubscriber.unsubscribe();
    routeSubscription.unsubscribe();
}

const userFillSubscriber = this.userObjectUnderEdit.subscribe(用户 => this.userFormFill = 用户); ^ 每当页面刷新时,用户为空。 但是,ngIf 仍然填充垫标签,因此 userObjectUnderEdit 仍然可以正常工作。

这可能是竞争条件问题。 userFillSubscriber 可能在订阅发出任何其他内容之前取消订阅,然后为 null。通常你只有在组件崩溃时才取消订阅(onDestroy)。或者您通过 take(x).

限制排放量

也许这会有所帮助:

const userFillSubscriber = this.userObjectUnderEdit
.pipe(filter(user => !!user), take(1))
.subscribe(user => 
this.userFormFill = user);

这两个.unsubscribe函数都不需要了。订阅在 1 次发射后停止,因为如果 take(1) operator.

    const userFillSubscriber = this.userObjectUnderEdit.subscribe(user => this.userFormFill = user);
    this.setEditFormValues(this.userFormFill);

您正在设置订阅块内的 属性 userFormFill 然后 运行

 this.setEditFormValues(this.userFormFill);

我打算借用T.van den Berg的代码稍微修改一下:

const userFillSubscriber = this.userObjectUnderEdit.pipe(
    filter(user => !!user), 
    take(1)
).subscribe(user => {
    this.userFormFill = user;
    this.setEditFormValues(this.userFormFill) // add this line inside your subscribe as well
});