【发布时间】:2018-02-08 14:13:42
【问题描述】:
我尝试使用 Angular 异步管道并让它显示我使用 http get 请求从服务器获取的时间。我有以下问题:
- 如果我想再次重新执行 http get 请求以获取更新的数据,那么在 testAsync() 中执行我正在执行的操作是否正确,或者是否有更优雅的方式来执行此操作?
- 我还注意到在使用异步管道和重新请求数据时出现了一些闪烁。这在非异步版本(“testNormal()”)中不会发生。有什么办法可以防止这种情况发生吗?
角度组件:
@Component({
selector: 'app-async-test',
templateUrl: './async-test.component.html',
styleUrls: ['./async-test.component.scss']
})
export class AsyncTestComponent implements OnInit {
private readonly baseApiUrl = environment.baseApiUrl;
httpServerRequest$ = this.http.get<ServerTimeViewModel>(`${this.baseApiUrl}/admin/servertime`);
testNormalResult: Date = null;
testAsyncResult$: Observable<Date> = null;
constructor(
private http: HttpClient
) {}
ngOnInit() {
this.testAsync();
}
testNormal(): void {
this.httpServerRequest$.subscribe(data => {
this.testNormalResult = data.serverTime;
});
}
testAsync(): void {
this.testAsyncResult$ = this.httpServerRequest$
.map(d => d.serverTime);
}
}
ServerTimeViewModel 类:
export class ServerTimeViewModel {
serverTime: Date;
}
模板:
Test normal: {{ testNormalResult | date:'mediumTime'}}<br>
Test async: {{ testAsyncResult$ | async | date:'mediumTime'}}<br>
<button type="button" (click)="testNormal()">test normal</button>
<button type="button" (click)="testAsync()">test async</button>
【问题讨论】:
标签: angular asynchronous rxjs observable