请帮助我订阅更改的变量。我简单地做了微调。服务中的Spinner状态(true | false)存储:
import { Injectable } from '@angular/core';
import { Response, Headers, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class GlobalVarsService {
private isVisibleSpinner: boolean = false;
getSpinnerState(): Observable<boolean> {
return this.isVisibleSpinner;
};
setSpinnerState(state): void {
console.log('setSpinnerState', state);
this.isVisibleSpinner = state;
};
}
在组件模板中,我通过条件显示微调器:
<div class="nav">
<a [routerLink]="['/select']">select</a>
<a [routerLink]="['/output']">output</a>
</div>
<router-outlet></router-outlet>
<div class="spinner-backdrop" *ngIf="isVisibleSpinner"></div>
<div class="spinner-area" *ngIf="isVisibleSpinner">
<span class="spinner">loading...</span>
</div>
在组件中我尝试订阅更改服务isVisibleSpinner变量:
import { Component } from '@angular/core';
import { Response } from '@angular/http';
import 'rxjs/add/operator/map'
import { GlobalVarsService } from './services/global-vars.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private isVisibleSpinner: boolean;
constructor(private globalVarsService: GlobalVarsService) {
this.globalVarsService.getSpinnerState().subscribe(data => {
console.log(data);
this.isVisibleSpinner = data;
});
}
}
但是控制台输出遵循以下错误消息:
输入&#39;布尔&#39;不能分配给&#39; Observable&#39;。
答案 0 :(得分:1)
因为您返回一个observable并将值放在boolean中,您可以将is变量的类型更改为Observable并使用异步管道获取值或映射您的&#34;数据&#34;如果那就是你想要的布尔值
export class AppComponent {
private isVisibleSpinner: Observable<boolean>;
constructor(private globalVarsService: GlobalVarsService) {
this.globalVarsService.getSpinnerState().subscribe(data => {
console.log(data);
this.isVisibleSpinner = data;
});
}
}
app.component.html
<div class="spinner-backdrop" *ngIf="isVisibleSpinner | async"></div>
<div class="spinner-area" *ngIf="isVisibleSpinner | async">
<span class="spinner">loading...</span>
</div>