如何从自定义确认装饰器访问自定义服务和对话框

How to access Custom service and dialog from custom confirm decorator

如何访问 angular 依赖项注入中的单例实例?

我想用这种方式为确认对话框编写自定义装饰器。
装饰器实现:

import {NgplDialogConfirmModel, NgplDialogService} from '../dialog';
import {take} from 'rxjs/operators';

export function Confirmable(options?: NgplDialogConfirmModel, confirm = 'confirmService') {

  // our factory function will return our actual decorator function, but now we have
  // an actual options object to configure our alert box :)
  return (target: Object, propertyKey: string, descriptor: PropertyDescriptor) => {
    // the usual, caching the original implementation
    const originalMethod = descriptor.value;
    // default values for our config, we’ll overwrite this with our options parameter

    console.log('target', target);
    console.log('propertyKey', propertyKey);
    console.log('descriptor.value', descriptor.value);
    console.log('target[confirm]', target[confirm]);
    const service: NgplDialogService = target &&  target[confirm];
    if (!service) {
     return descriptor;
    }
    descriptor.value = function(...args: any[]) {
      const dialogRef = service.confirm(options);
      return dialogRef
        .pipe(
          take(1)
        )
        .subscribe((confirmed: boolean) => {
          if (!!confirmed) {
            originalMethod.apply(this, ...args);
          }
        });
    };
    return descriptor;

  };

}

此处使用

  @Confirmable()
  confirmDelete(action): void {
    console.log('action', action);
  }

我有自己的服务,集成了 matDialog 并确认我在任何地方使用的操作。


@Injectable({
  providedIn: 'root'
})
export class NgplDialogService {

  constructor(private dialog: MatDialog) {
  }

  public confirm(data: any= {}): Observable<boolean> {
    data.title = data.title || 'Confirm';
    data.message = data.message || 'Are you sure?';
    data.showCancel = data.showCancel || true;
    data.showIcon = data.showIcon || true;

    let dialogRef: MatDialogRef<ConfirmComponent>;
    console.log('this.dialog', this.dialog);
    dialogRef = this.dialog.open(ConfirmComponent, {
      width: '480px',
      disableClose: true,
      data,
      backdropClass: 'confirm-backdrop-class',
      panelClass: 'confirm-panel-class'
    });
    return dialogRef.afterClosed();
  }
}

我尝试了一些方法,例如 Injertor.create 和 ReflectiveInjector(已弃用),但我无法访问我的服务实例。

我试图从装饰器访问注入到组件内部的确认服务,但装饰器在组件依赖注入完成之前执行。

在网上看了好几遍同样的文章,又看了一遍这篇,https://medium.com/capital-one-tech/custom-typescript-decorators-using-rxjs-and-angular-services-6ddd1079f683, and I understood better that approach and I tried it in my stackbliz code, and Its works. https://stackblitz.com/edit/angular-ivy-2bpgfc?file=src%2Fapp%2Fapp.component.ts