0

我需要创建 canDeactiovateGuard 以防止用户在尝试离开表单页面时丢失表单数据。下面的代码不起作用,因为 return canDeactivate 在 canDeactivate = 确认之前起作用。我不知道如何解决这个问题。

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<Component> {

  canDeactivate(component: Component): boolean {
    let canDeactivate: boolean;
    if (component.formValueChanged) {
        component.confirmService.confirm("You have unsaved data. Are you sure?")
            .pipe(first())
            .subscribe((confirmed: boolean) => {
                canDeactivate = confirmed;
            });
    } else {
        canDeactivate = true;
    }
    return canDeactivate;
  }

}
4

1 回答 1

2

而是尝试返回一个Observable<boolean>. 这可以通过诸如 RxJS map 之类的操作符来完成。无论哪种方式,在 CanDeactivate 或 CanActivate 等守卫中,基本上你永远不会使用subscribe(),因为你不能从 a 中返回任何东西subscribe(),而是返回Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree

import { map } from 'rxjs/operators';

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<Component> {

  canDeactivate(component: Component): Observable<boolean> | boolean {
    if (component.formValueChanged) {
        // Return the observable instead of the subscription
        return component.confirmService.confirm("You have unsaved data. Are you sure?")
            .pipe(first())
            // You may be able to remove map() assuming confirm() always returns Observable<boolean>
            .map((confirmed: boolean) => confirmed);
    }

    return false;
  }
}
于 2020-02-12T16:08:26.313 回答