如何在angular中提供和注入函数?

How to provide and inject functions in angular?

我有我需要在任何组件中注入的功能:

export const matDialogCallbacks = (dialog: MatDialog, document: Document, renderer: Renderer2) => {
    dialog.afterOpened.subscribe(() => renderer.addClass(document.body, 'overflow-hidden'));
    dialog.afterAllClosed.subscribe(() => renderer.removeClass(document.body, 'overflow-hidden'));
};

我需要注入并使用:

 constructor(private matDialogCallbacks: matDialogCallbacks, private dialog: MatDialog) {
    matDialogCallbacks(dialog);
}

怎么做?

我做了服务:

import { Injectable, Inject, Renderer2 } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DOCUMENT } from '@angular/common';

@Injectable({
    providedIn: 'root',
})
export class DialogEventsService {
    constructor(@Inject(DOCUMENT) private document: Document, private renderer: Renderer2) {}

    init(dialog: MatDialog) {
        dialog.afterOpened.subscribe(() => this.renderer.addClass(this.document.body, 'overflow-hidden'));
        dialog.afterAllClosed.subscribe(() => this.renderer.removeClass(this.document.body, 'overflow-hidden'));
    }
}

当我尝试在组件中使用此服务时,我得到:

NullInjectorError: R3InjectorError(OrdersDistributionModule)[DialogEventsService -> DialogEventsService -> Renderer2 -> Renderer2 -> Renderer2]: 

定义函数类型:

type dialogCB= (dialog: MatDialog, document: Document, renderer: Renderer2) => void

现在函数:

export const matDialogCallbacks :dialogCB = (dialog: MatDialog, document: Document, renderer: Renderer2) => {

      dialog.afterOpened.subscribe(() => renderer.addClass(document.body, 'overflow-hidden'));

      dialog.afterAllClosed.subscribe(() => renderer.removeClass(document.body, 'overflow-hidden'));
};

现在创建一个令牌:

import { InjectionToken } from '@angular/core';

export const TOKEN_NAME = new InjectionToken<dialogCB>('dialog callback');

现在在根模块中提供它:

providers: [{ provide: TOKEN_NAME, useValue: matDialogCallbacks  }]

终于可以注入了:

constructor(@Inject(TOKEN_NAME) private matDialogCallbacks: dialogCB, private dialog: MatDialog) {
matDialogCallbacks(dialog);

}