获取bool数据的更新值
问题描述:
我正在使用angular 2.我提供了一个服务,我想执行一个简单的任务,就像我在两个组件中创建服务对象一样。在component1将bool值更改为true时,我想使用该值,因为它在component2中。反之亦然。获取bool数据的更新值
我的服务是:
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的变化值在提供服务呈现。
答
而不是提供service
在component
级别,请在您的module
级别提供它。通过这种方式,您的service
将变成单身,并且在一个component
处更改值将会反映在另一个component
中。
@NgModule({
declarations: [
AppComponent
],
imports: [
],
providers: [JwtService],
exports: [],
bootstrap: [AppComponent]
})
答
您可以使用behaviourSubject
,参考可以找到here。
你应该做的是使appStatus
作为behaviourSubject
服务。然后,您将从您的component2订阅它的价值。现在,当您在component1中设置其状态时,component2将检测到更改的值,并且将触发component2中订阅内的功能。
答
看来你对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);
}
}
@Haseoh - >你忘了提,你必须提供JwtService在NgModule和删除供应商:JwtService]由两个组件。这样,每个组件就会有一个JwtService实例,而不是2个分离服务。 – mehul