如何在角度依赖注入中访问该单例实例?
我想用这种方式为确认对话框编写自定义装饰器。
装饰器实现:
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),但我无法访问我的服务实例。