0

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

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]: 
4

1 回答 1

1

定义函数类型:

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);

}

于 2020-12-22T16:26:37.243 回答