我花了最后几天试图从AngularJS转移到Angular。我已经有了一个网络应用程序,我想重写它以进行锻炼。我在旧版本中使用的一个功能是在HTTP请求期间加载微调器。我搜索了谷歌和在线教程,看看我如何用Angular做到这一点,我选择了一项服务。这是代码:
spinner.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
export interface ISpinnerState {
show: boolean
}
@Injectable()
export class SpinnerService {
private _spinnerSubject = new Subject();
spinnerState = <Observable<ISpinnerState>>this._spinnerSubject;
show() {
this._spinnerSubject.next(<ISpinnerState>{ show: true });
}
hide() {
this._spinnerSubject.next(<ISpinnerState>{ show: false });
}
}
spinner.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { ISpinnerState, SpinnerService } from './spinner.service';
@Component({
selector: 'loading-spinner',
template: `
<div
class="spinner">
</div>
`,
styles: [`.spinner {position: absolute;left: 46%;top: 12%;background-color:black;width:50px;height:50px}`]
})
export class SpinnerComponent implements OnDestroy, OnInit {
visible = false;
private _spinnerStateChanged: Subscription;
constructor(private _spinnerService: SpinnerService) { }
ngOnInit() {
this._spinnerStateChanged = this._spinnerService.spinnerState
.subscribe((state: ISpinnerState) => this.visible = state.show);
}
ngOnDestroy() {
this._spinnerStateChanged.unsubscribe();
}
}
此刻,它只是一个黑色方块,所以我可以测试它。之后,我将添加一个正确的加载图标。这是我在HTTP请求期间调用它的另一项服务。
apartment.service.ts
....other stuff
@Injectable()
export class ApartmentService {
constructor(
private _http: Http,
private _spinnerService: SpinnerService
) { }
getApartments() {
this._spinnerService.show();
return this._http.get(API + 'apartments')
.map((response: Response) => <Apartment[]>response.json().apartments)
//.catch(this._exceptionService.catchBadResponse)
.finally(() => this._spinnerService.hide());
}
}
问题在于微调器始终可见。不仅在装载过程中。我看不出我做错了什么。有什么想法吗?
答案 0 :(得分:2)
我认为你缺少显示/隐藏的绑定,具体取决于visible
状态:
<div *ngIf="visible"
class="spinner">
</div>