在我的app.component.html中,

<div class="main">
    <button type="button" (click)="onShowNotificationSideBar()" label="Show"></button>  
    <p-sidebar [(visible)]="notificationSideBarVisible" position="right" [style]="{width:'50em'}">
        <button type="button" pButton pRipple (click)="showSuccess()" label="S" class="p-button-success"></button>        
        <button type="button" pButton pRipple (click)="showWarn()" label="W" class="p-button-warning"></button>
        <button type="button" pButton pRipple (click)="showError()" label="E" class="p-button-danger"></button>
        <h3>Messages</h3>
        <h5>{{messages}}</h5>
        <p-messages [(value)]="messages" [enableService]="false" ></p-messages>
    </p-sidebar>
    <p-toast position="center"></p-toast>
    <router-outlet></router-outlet>
</div>

在app. component. ts中,

import { Component } from '@angular/core';
import { Message, MessageService } from 'primeng/api';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [MessageService]
})
export class AppComponent {
  title = 'WECO';
  notificationSideBarVisible = false;

  constructor(private messageService: MessageService) {
    messageService.messageObserver.subscribe((m:Message | Message[])=>{
      if (!Array.isArray(m)){
        this.messages.push(m)
      }
      this.messages = [...this.messages];
    });
  }

  onShowNotificationSideBar(){
    this.notificationSideBarVisible=true;
  }

  count=0;

  messages : Message[] = [
    // { severity: 'success', summary: 'Success', detail: 'Message Content' },
    // { severity: 'info', summary: 'Info', detail: 'Message Content' },
    // { severity: 'warn', summary: 'Warning', detail: 'Message Content' },
    // { severity: 'error', summary: 'Error', detail: 'Message Content' }
  ];

  longSentence = 'Let’s end all this nonsense about how long sentences = run-on sentences. You can have a six-word run-on sentence (“I went shopping I ate donuts.”), while most of the sentences below are much, much longer than that and are not run-ons';//'And let’s end all this nonsense about how long sentences = run-on sentences. You can have a six-word run-on sentence (“I went shopping I ate donuts.”), while most of the sentences below are much, much longer than that and are not run-ons (except for a few examples like Jose Saramago).  But whether the sentence is grammatically correct isn’t nearly as important as whether the sentence is fun or beautiful.'

  showWarn(){
    let detail='User Deleted a Weco Rule';
    if (this.count++%5===0)
      detail = this.longSentence;
    this.messageService.add({severity:'warn', summary:'User Action', detail: detail});
  }

  showSuccess(){
    let detail = 'Weco Rule 123 Saved';
    if (this.count++%5===0)
      detail = this.longSentence;
    this.messageService.add({severity:'success', summary:'Service Call', detail:detail});
  }

  showError(){
    let detail = 'api-call:get-factories returned 404';
    if (this.count++%5===0)
      detail = this.longSentence;
    this.messageService.add({severity:'error', summary:'Service Call', detail:detail});
  }
}

如果我打开边栏并添加一些消息,它们就会出现,但当我关闭并重新打开时,它们就消失了. 即使我可以看到消息变量仍然有它们.为什么?
P.S. 如果我再添加一些消息,我只能看到新的消息.

推荐答案

侧边栏菜单有一个名为p-messages的组件,如果你判断该元素,你会注意到,当你关闭时,p-sidebar的内容会被销毁.

当您重新打开侧边栏时,数据保持不变,但消息被销毁.

我认为p-messages组件只会显示数组引用正在改变,这可能是由于组件内部的*ngFortrackBy,所以我们需要重置内存中的每个数组元素引用,这样我们就可以欺骗p-messages,让它认为列表中有新的消息,为此我们可以使用对象解构!我会在打开侧边栏时这样做(onShowNotificationSideBar)

onShowNotificationSideBar() {
    this.notificationSideBarVisible = true;
    this.messages = [...this.messages.map(x => ({...x}))]; // <- creates new references for the array and its contents!
}

完整代码

import { Component } from '@angular/core';
import { Message, MessageService } from 'primeng/api';

@Component({
  selector: 'sidebar-basic-demo',
  templateUrl: './sidebar-basic-demo.HTML',
  providers: [MessageService],
})
export class SidebarBasicDemo {
  title = 'WECO';
  notificationSideBarVisible = false;

  constructor(private messageService: MessageService) {
    messageService.messageObserver.subscribe((m: Message | Message[]) => {
      if (!Array.isArray(m)) {
        this.messages.push(m);
      }
      this.messages = [...this.messages];
    });
  }

  onShowNotificationSideBar() {
    this.notificationSideBarVisible = true;
    this.messages = [...this.messages.map(x => ({...x}))];
  }

  count = 0;

  messages: Message[] = [
    // { severity: 'success', summary: 'Success', detail: 'Message Content' },
    // { severity: 'info', summary: 'Info', detail: 'Message Content' },
    // { severity: 'warn', summary: 'Warning', detail: 'Message Content' },
    // { severity: 'error', summary: 'Error', detail: 'Message Content' }
  ];

  longSentence =
    'Let’s end all this nonsense about how long sentences = run-on sentences. You can have a six-word run-on sentence (“I went shopping I ate donuts.”), while most of the sentences below are much, much longer than that and are not run-ons'; //'And let’s end all this nonsense about how long sentences = run-on sentences. You can have a six-word run-on sentence (“I went shopping I ate donuts.”), while most of the sentences below are much, much longer than that and are not run-ons (except for a few examples like Jose Saramago).  But whether the sentence is grammatically correct isn’t nearly as important as whether the sentence is fun or beautiful.'

  showWarn() {
    let detail = 'User Deleted a Weco Rule';
    if (this.count++ % 5 === 0) detail = this.longSentence;
    this.messageService.add({
      severity: 'warn',
      summary: 'User Action',
      detail: detail,
    });
  }

  showSuccess() {
    let detail = 'Weco Rule 123 Saved';
    if (this.count++ % 5 === 0) detail = this.longSentence;
    this.messageService.add({
      severity: 'success',
      summary: 'Service Call',
      detail: detail,
    });
  }

  showError() {
    let detail = 'api-call:get-factories returned 404';
    if (this.count++ % 5 === 0) detail = this.longSentence;
    this.messageService.add({
      severity: 'error',
      summary: 'Service Call',
      detail: detail,
    });
  }
}

HTML

<div class="main">
  <button type="button" (click)="onShowNotificationSideBar()" label="Show">
    show sidebar
  </button>
  <p-sidebar
    [(visible)]="notificationSideBarVisible"
    position="right"
    [style]="{width:'50em'}"
  >
    <button
      type="button"
      pButton
      pRipple
      (click)="showSuccess()"
      label="S"
      class="p-button-success"
    >
      success
    </button>
    <button
      type="button"
      pButton
      pRipple
      (click)="showWarn()"
      label="W"
      class="p-button-warning"
    >
      warn
    </button>
    <button
      type="button"
      pButton
      pRipple
      (click)="showError()"
      label="E"
      class="p-button-danger"
    >
      error
    </button>
    <h3>Messages</h3>
    <h5>{{messages}}</h5>
    <p-messages [(value)]="messages" [enableService]="false"></p-messages>
  </p-sidebar>
  <p-toast position="center"></p-toast>
</div>

Stackblitz Demo

Angular相关问答推荐

如何从Angular TS文件传递$Events对象?

日语字符不受角形约束控制

iOS Mobile Safari - HTML5视频覆盖一切

未在ng bootstrap 模式中设置表单输入

访问Angular 模板中的HTML元素属性

茉莉花-模板中调用了如何判断角管

material 对话框中没有合适的注塑

我正在try 将一个带有模块联盟的Angular 8项目expose 到另一个Angular 项目,Angular 是15,这可能吗?如果是这样,有什么建议吗?

Angular 单调服务已多次创建

nx serve正在忽略@angular/localize/init的导入"

Angular 16模块中未使用的组件是否从Bundle 包中删除(树摇动)?

无法创建新的 Ionic 项目

从 applescript 调用Angular 前端以从列表中 Select 一个项目

重新打开模态时 ng-select 中的重复值 - Angular

使用 RXJS 进行空闲/不活动跟踪

使用directive指令将类添加到host元素中

使用 rxjs 处理刷新令牌

Angular CLI 输出 - 如何分析Bundle 文件

RxJS - 发生错误时观察到的不会完成

如何作为模块的子模块路由到模块 - Angular 2 RC 5