Reputation: 127
Please help my subscribe to changed variable. I make simply spinner. Spinner state(true|false) storage in service:
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;
};
}
In component-template i display spinner via condition:
<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>
In component i try subscribe to change in service isVisibleSpinner variable:
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;
});
}
}
But console output follow eror message:
Type 'boolean' is not assignable to type 'Observable'.
Upvotes: 0
Views: 1431
Reputation: 1083
because you are returning an observable and putting the value in boolean, you can change the type of your is variable to Observable and use the async pipe to get the value or map your "data" to boolean if thats what you want
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>
Upvotes: 1