简体   繁体   中英

service not singleton inside MatDialog module

When I open a Mat Dialog popup ( angular material ) and accessing a singleton service, for some reason inside the mat dialog the service seems to be a new instance of the service and not the singleton service used across the app.

I know how to make workaround but I prefer understanding if there is a known issue with matdialog and maybe a fix.

  const dialogRef = this.dialog.open(MyComponent, {
  width: '400px',
  data: {
    myInfo: Info
  },
});

The service was added in the "App.component.ts" as a singleton like this:

import {Component, OnInit} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
import {AuthService} from './shared/services/auth.service';
@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.scss'],  

providers: [AuthService]})    export class AppComponent implements OnInit {}

Thanks!

As far as I know, the problem is that you are declaring service inside AppComponent , but material dialogs are spawning outside your app-root ( angular cdk is spawning as last element in body ) so it's not available for your dialog component . To fix this you should declare provider AuthSerivce inside your main AppModule then it will be visible in your dialog component.

I am running into the same issue. Have you had any answers to this question? I'm also using mat-dialog, when i call a service (with providedIn root), the dialog creates a new instance of the service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM