如何将布尔值从服务发送到组件。这个布尔值正在 2 个函数(onStartBlockUI 和 onStopBlockUI(中更改他的值。对于第一个函数,onStartBlockUI 这个布尔值是真的,对于第二个函数,onStopBlockUI 这个布尔值是假的。我想在组件的订阅中获取此值。我将不胜感激任何帮助。谢谢!
import { Component, OnInit } from '@angular/core';
import { LoadingService } from './loading.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-loading',
templateUrl: './loading.component.html',
styleUrls: ['./loading.component.scss'],
providers: [LoadingService]
})
export class LoadingComponent implements OnInit {
private blockUIState: boolean;
private subscriptionBlockUI: Subscription;
constructor(private loadingService: LoadingService) {
this.subscriptionBlockUI = this.loadingService.onBlockUIState().subscribe(blockUIState => {
this.blockUIState = blockUIState;
console.log('this.blockUIState', this.blockUIState);
});
}
ngOnInit() {
}
ngOnDestroy(): void {
this.subscriptionBlockUI.unsubscribe();
}
}
import { Injectable } from '@angular/core';
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
@BlockUI() blockUI: NgBlockUI;
public blockUIState = new Subject<boolean>();
constructor() {
this.onStartBlockUI();
this.onStopBlockUI();
}
onStartBlockUI(): void {
this.blockUI.start('Start loading...');
this.blockUIState.next(true);
}
onStopBlockUI(): void {
setTimeout(() => {
this.blockUI.stop(); // Stop blocking
}, 2000);
this.blockUIState.next(false);
}
onBlockUIState(){
return this.blockUIState;
}
}
我认为您想使用BehaviorSubject
而不是Subject
。
行为主体重播每个订阅的实际值,您可能会错过组件中的第一个值
您需要将其更改为
onStopBlockUI(): void {
setTimeout(() => {
this.blockUIState.next(false);
this.blockUI.stop(); // Stop blocking
}, 2000);
}
因为 setTimeout(( 的内部函数在给定的时间(此处为 2000(之后执行。