0

如何在角度依赖注入中访问该单例实例?

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

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(deprecated),但我无法访问我的服务实例。

我试图从装饰器访问组件内部注入的confirmService,但装饰器在组件依赖注入完成之前执行。 在此处输入图像描述

4

1 回答 1

1

在互联网上阅读了几篇相同的文章后,我再次阅读了这篇文章,https://medium.com/capital-one-tech/custom-typescript-decorators-using-rxjs-and-angular-services-6ddd1079f683和我更好地理解了这种方法,并在我的 stackbliz 代码中尝试了它,它的工作原理。https://stackblitz.com/edit/angular-ivy-2bpgfc?file=src%2Fapp%2Fapp.component.ts

于 2021-07-26T21:47:52.720 回答