我在Angular 2项目中使用Ng-Spin-kit。
在组件中我有此代码:
loading: boolean;
setTimeout(() => { this.loading = true },
1000
);
,在html中,我有一个:
<sk-fading-circle class="loader" [hidden]="loading"></sk-fading-circle>
所以,我使旋转器运行,但仅运行1000ms。
我需要旋转器才能运行直到加载API的内容。
我不知道setTimeout()
是否是这样做的最佳方法。
有人知道我该怎么做吗?
update
这是服务
export class AppService {
endPoint = AppConstants;
handler = AppHandler;
constructor(private http: Http) {}
getCandidates() {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
return this.http.get(this.endPoint.API_ENDPOINT_GET_CANDIDATES, {
headers: headers
})
.toPromise()
.then((res: Response) => {
const data = res.json();
const allCandidate = [];
data.result.forEach((entry) => {
const candidate = new Candidate();
candidate.college = entry.college;
candidate.cultural_fit = entry.cultural_fit;
candidate.email = entry.email;
candidate.graduation = entry.graduation;
candidate.logic_test = entry.logic_test;
candidate.mobile_phone = entry.mobile_phone;
candidate.name = entry.name;
allCandidate.push(candidate);
});
return allCandidate;
})
.catch(this.handler.handleError);
}
}
这就是我的方式
loading: boolean = false;
getCandidates() {
// ...
this.loading = true;
return this.http.get(this.endPoint.API_ENDPOINT_GET_CANDIDATES, {
headers: headers
}).map(res => res.json())
.catch(this.handler.handleError)
.finally(() => this.loading = false)
.subscribe(res => {
// ...
});
}
几乎没有选项,主要选项是:
- 使用可观察的可检索数据中的数据(这是已经是Angular http的一部分(,订阅并将加载设置为检索数据/错误后 false
- 完成后要执行的回调函数。
首先您应该使用 *ngif:
<sk-fading-circle class="loader" *ngIf="loading"></sk-fading-circle>
在组件中使用
loading: boolean = true;
如果您的API使用可观察到的,那么您的代码应该看起来像:
this.api.subscribe(data => ....
...
() => {this.loading = false});
一旦加载数据就会导致旋转器删除。