【发布时间】:2017-02-12 21:47:25
【问题描述】:
我在最后几天尝试从 AngularJS 迁移到 Angular。我已经有一个网络应用程序,我想重写它以进行锻炼。我在旧版本中的一项功能是在 HTTP 请求期间加载微调器。我在 Google 和在线教程上进行了搜索,以了解如何使用 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());
}
}
问题是微调器总是可见的。不仅在加载过程中。我看不出我做错了什么。有什么想法吗?
【问题讨论】:
-
我认为
spinnerState = <Observable<ISpinnerState>>this._spinnerSubject;应该是spinnerState = <Observable<ISpinnerState>>this._spinnerSubject.asObservable(); -
你们在哪里提供服务?
-
您在哪里使用
visible来显示/隐藏微调器? -
@GünterZöchbauer 如果我更改代码,我会出现此错误:
[ts] Property 'asObservable' does not exist on type 'Subject<{}>'.我在哪里提供服务是什么意思? -
这很奇怪。我敢肯定,这应该只是工作。 github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/…
标签: angular