函数在 ngOnInit 中只传递一次

Har*_*rry 0 typescript angular

我开发了一项服务,允许我激活按钮并查看其在不同组件中的状态。当我单击开始/暂停时,按钮会更改图像。

在 StackBlitz 中,代码运行良好,但是当我在我的项目中实现它时,该函数只传入一次ngOnInit并且不再加载,不再更改组件之间的按钮图像。

有没有办法实现这个但不使用ngOnInit

我用过setinterval,按钮改变了图像,但它似乎不是最好的解决方案。

谁能帮我?

闪电战

问题 --- 关于组件

currentState: string;
ngOnInit() {
    this.currentState = this.servicesService.getCurrentState();
}
Run Code Online (Sandbox Code Playgroud)

html

<div class="container" style="margin-top: 10%">
    <div class="btn-group" dropdown>
        <button id="button-basic" dropdownToggle type="button" class="btn ">
            <img style="width: 35px;" *ngIf="currentState=='pause'" src="https://img.icons8.com/carbon-copy/100/000000/play-button-circled.png">
            <img style="width: 35px;" *ngIf="currentState=='start'" src="https://img.icons8.com/cute-clipart/64/000000/stop-squared.png">
        </button>
        <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button-basic">
            <li role="menuitem">
              <a class="dropdown-item" *ngIf="currentState=='pause'" routerLinkActive="active" (click)="startTimer()">Start</a>
            </li>
            <li role="menuitem">
              <a class="dropdown-item" *ngIf="currentState=='start'" routerLinkActive="active" (click)="pauseTimer()">Stop</a>
            </li>
        </ul>
        <div>
            <span>{{servicesService.fetchDisplay()}}</span>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

成分

 startTimer() {
    this.servicesService.startTimer();
    this.currentState = this.servicesService.getCurrentState();
 }

 pauseTimer() {
    this.servicesService.pauseTimer();
    this.currentState = this.servicesService.getCurrentState();
 }
Run Code Online (Sandbox Code Playgroud)

Ash*_*yan 5

您可以将您的服务定义为公开

constructor(public servicesService: ServicesService) { }
Run Code Online (Sandbox Code Playgroud)

并在您的 html 中

*ngIf="servicesService.getCurrentState()=='pause'" 
Run Code Online (Sandbox Code Playgroud)