ng如果不重新启用变量值更改

时间:2018-08-27 14:51:37

标签: angular typescript

当我从另一组件调用将变量设置为true的方法时,我有一个简单的布尔值boolean来显示/隐藏div。

我的messages-refresh.component.html:

<div class="divOpacity" *ngIf="show">
<div class="boxMessageModal">
    <p>Novos dados foram encontrados para esta página, clique em Ok para atualizar!</p>
    <button class="btnOktoReload" (click)="reloadPage()">Ok</button>
</div>

我的messages-refresh.component.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-messages-refresh',
  templateUrl: './messages-refresh.component.html',
  styleUrls: ['./messages-refresh.component.css']
})

export class MessagesRefreshComponent implements OnInit {

  constructor(private location:Location) { }

  reloadPage(){
    location.reload(true)
  }

  show:boolean = false
  showDivOpacity(){
    this.show = true
  }

  ngOnInit() {
  }

}

我在另一个组件中将方法showDivOpacity称为this.messagesRefreshComponent.showDivOpacity()

1 个答案:

答案 0 :(得分:1)

您有不同的实例,因为您尝试对组件使用注入。

您必须尝试使用​​带有BehaviorSubject的注入类单例,这将仅提供一个具有存储的实例来保存对象或值,并通过注入将其获取到每个组件中

import { Injectable, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class SettingsService {
  private showSubject = new BehaviorSubject<boolean>(false);

  setUpdateShow(){
      this.showSobject.next(!showSobject.getValue());
  }

  isShowing$(){
     this.showSobject.asObservable();
  }
}

然后在组件中注入值

显示主题的Components.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-messages-refresh',
  templateUrl: './messages-refresh.component.html',
  styleUrls: ['./messages-refresh.component.css']
})

export class MessagesRefreshComponent implements OnInit {

  constructor(private settingsService:SettingsService ) { }
 show$: Observable<boolean>()
 ngOnInit() {
   this.show$ = this.settingsService.isShowing$();
 }
}

HTML

<div class="divOpacity" *ngIf="show$ | async">
<div class="boxMessageModal">
    <p>Novos dados foram encontrados para esta página, clique em Ok para atualizar!   </p>
    <button class="btnOktoReload" (click)="reloadPage()">Ok</button>
</div>

要调用或修改主题,必须注入服务并调用 setUpdateShow()函数,希望对您有所帮助。有点难以理解,但这是使它们之间不相关的组件通讯的最佳解决方案。