获取布尔数据的更新值

Get Updated value of an bool data

我正在使用 angular 2. 我做了一个服务,我想执行一个简单的任务,就像我在两个组件中创建服务对象一样。在 component1 将 bool 值更改为 true 的位置,我想使用该值,因为它在 component2 中。反之亦然

我的服务是:

import { Injectable } from '@angular/core';


@Injectable()
export class JwtService {

   appStatus:boolean=false;


  setStatus(value){
    debugger;

    this.appStatus = value;

  }
  getStatus(){


    return this.appStatus;
  }



}

在我的组件 1:

import { Component } from '@angular/core';

import { JwtService} from '../shared/services/jwt.service';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [JwtService ]
})
export class AppComponent {





appStatus: boolean = false; 
 constructor( private jwtService:JwtService) { }


 public Func() :any{


      this.jwtService.setStatus(false);


    }

}

在我的组件 2:

import { Component, OnInit } from '@angular/core';
import { JwtService} from '../services/jwt.service'
@Component({
  selector: 'layout-header',
  templateUrl: './header.component.html',
  providers: [JwtService]
})

export class HeaderComponent implements OnInit {
    appStatus: boolean ; 
  constructor(  private jwtservice:JwtService

  ) { 
this.appStatus=jwtservice.getStatus();

   }

 setout()
{



  this.jwtservice.setStatus(true);


}



}

只想获取在服务中显示的 appstatus 的更改值。

您可以使用behaviourSubject,可以找到参考here

你应该做的是 appStatus 在你的服务中作为 behaviourSubject。然后你将从你的 component2 订阅它的值。现在当你在component1中设置它的状态时,component2会检测到变化的值,并触发component2中订阅里面的函数。

与其提供 component 级别的 service,不如提供 module 级别的级别。通过这种方式,您的 service 将成为单例,更改一个 component 的值将反映在另一个 component.

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
  ],

  providers: [JwtService],

  exports: [],
  bootstrap: [AppComponent]
})

看来你对RxJS不是很熟悉。 您可以将appStatus 转换为您可以订阅的Subject。基本上,您将回调传递给 Subject ,每次值更改时都会调用它。 Subject.next(value) 用于设置新值。

注意:当组件被销毁时,您必须取消订阅主题。这将防止内存泄漏和未定义的行为。

服务:

@Injectable()
export class JwtService {
   appStatus = new BehaviorSubject<boolean>();
}

两个组件:

export class HeaderComponent implements OnInit, OnDestroy {
  private _sub: Subscription;
  private _currentStatus: boolean = false;
  constructor(private service:JwtService) {}
  ngOnInit() {
    // We make subscription here. Behavior subject means that you will receive latest value on subscription and every next value when it is changed.
    this._sub = this.service.appStatus.subscribe((status) => this._currentStatus = status);
  }
  ngOnDestroy() {
    // IMPORTANT: UNSUBSCRIBE WHEN COMPONENT IS DESTROYED
    this._sub.unsubscribe();
  }
  setStatus(status: boolean) {
    this.service.appStatus.next(status);
  }
}