providedIn: 'platform' but with dependencies injected in root

Viewed 394

I have an angular 9 application with service that open a snackbar.
and I have an angular element embedded in my app.
I'm trying to let the angular element use that service, so I injected it in 'platform'.
The problem is that the dependency of that service (MatSnackBar) is provided in MatSnackBarModule which imported in my AppModule, hence I get NullInjectorError: No provider for MatSnackBar.

here my code:

import { Injectable } from '@angular/core';
import {
    MatSnackBar, MatSnackBarConfig, MatSnackBarRef, SimpleSnackBar
} from '@angular/material/snack-bar';


@Injectable({ providedIn: 'platform' })
export class ToasterService {

    private ref: MatSnackBarRef<SimpleSnackBar>;
    constructor(private snackbar: MatSnackBar) { }

    commonConfig: MatSnackBarConfig = {
        duration: 3000,
        verticalPosition: 'top',
        horizontalPosition: 'left'
    };

    error(message: string) {
        this.open(message, 'error');
    }
    success(message: string) {
        this.open(message, 'success');
    }

    private open(message: string, panelClass: string) {
        this.ref = this.snackbar.open(
            message, null, { ...this.commonConfig, panelClass }
        );
    }
}

and here is the error I got

main.ts:14 NullInjectorError: R3InjectorError(AppModule)[ToasterService -> ToasterService -> ToasterService -> MatSnackBar]: 
  NullInjectorError: No provider for MatSnackBar!
    at NullInjector.get (http://localhost:4200/vendor.js:67430:27)
    at R3Injector.get (http://localhost:4200/vendor.js:81146:33)
    at injectInjectorOnly (http://localhost:4200/vendor.js:67285:33)
    at Module.ɵɵinject (http://localhost:4200/vendor.js:67295:57)
    at Object.ToasterService_Factory [as factory] (http://localhost:4200/main.js:296:147)
    at R3Injector.hydrate (http://localhost:4200/vendor.js:81382:63)
    at R3Injector.get (http://localhost:4200/vendor.js:81134:33)
    at R3Injector.get (http://localhost:4200/vendor.js:81146:33)
    at R3Injector.get (http://localhost:4200/vendor.js:81146:33)
    at NgModuleRef$1.get (http://localhost:4200/vendor.js:98478:33)

P.S. this error occure even without the angular element, but also when a regular component injeced that service.
P.S. this error occure only when I'm providing the service in 'platform'. If I'm providing the service in 'root' everything works fine.

Does the feature providedIn 'platform' is not suitable for this situation?
There is any way to bypass this issue?
Anyone know another way to achieve what I'm trying?

Thanks so much!

0 Answers
Related