是否可以从另一个服务调用 ConfirmationService

Is it possible to call ConfirmationService from another Service

我想声明一个应用程序范围的 PrimeNg(即:在 app.component.html 内),然后能够通过从另一个服务调用 ConfirmationService.confirm() 来显示它。 请在app-component.html

中找到代码HTML
<p-confirmDialog
[key]="mainDialog"
class="styleDialog"
[baseZIndex]="10000"
> </p-confirmDialog>

然后我创建服务dialogue.service.ts

@Injectable({providedIn: 'root', })    

  export class FooService{

  constructor(
  
   private confirmationService: ConfirmationService,`

    ) {}

  doSomeStuff() {

  this.confirmationService.confirm({
  key:'mainDialog',
  message: 'some message',
  header: 'Warning',
  icon: 'pi pi-exclamation-triangle',
  acceptLabel: 'ok',
  rejectVisible: false,
  accept: () => {},
  });
}
 } ` 

--> 但这不起作用。请问我遗漏了什么吗?

非常感谢您的回复

好的。所以第一个问题是您使用 key 作为指令(所以 [key])。这意味着在内部你必须写一个 属性 在组件中声明。在这种情况下,您可以直接使用一个字符串,因此以这种方式更改您的 HTML:

<p-confirmDialog key="mainDialog" class="styleDialog" [baseZIndex]="10000">
    Content
</p-confirmDialog>

然后,在您 app.module.ts 中,您应该添加 ConfirmationService:

作为提供者
@NgModule({
  declarations: [
    AppComponent,
...
  ],
  imports: [
...
    ConfirmDialogModule
  ],
  providers: [ConfirmationService],
  bootstrap: [AppComponent]
})

最后,我注意到您的 FooService 中有一个错误。我想这与您在 Whosebug 上的 copy/paste 有关,但是让我也把它写下来。

import {Injectable} from '@angular/core';
import {ConfirmationService} from 'primeng/api';

@Injectable({
  providedIn: 'root'
})
export class FooService {

  constructor(private confirmationService: ConfirmationService) {
  }

  confirm(): void {
    this.confirmationService.confirm({
      key: 'mainDialog',
      message: 'some message',
      header: 'Warning',
      icon: 'pi pi-exclamation-triangle',
      acceptLabel: 'ok',
      rejectVisible: false,
      accept: () => {
        console.log('accept');
      },
    });
  }
}

不要忘记在需要的地方声明和调用 FooService.confirm 方法。假设您在 app.component.ts 中需要它,您将得到如下内容:

import {Component, OnInit} from '@angular/core';
import {FooService} from './foo.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private fooService: FooService) {
  }

  ngOnInit(): void {
    this.fooService.confirm();
  }
}