正在后台从 API 加载数据

Loading data from API in background

我目前正在努力改进我的用户体验。 当用户切换到新组件时,大约需要 0.5 到 1 秒,直到他们的数据被加载并显示在视图中。所以一开始,视图是空的,有些部分丢失或显示错误。

我了解到有 angular 解析接口。然而据我了解,它只是延迟视图的呈现,直到数据可用。

我想知道是否有一个选项,您可以在呈现我的应用程序的着陆页后在后台加载数据。通过这种方式,用户已经可以使用和查看该应用程序,并且在后台他们不会注意到另一个 pages/components 的数据正在加载。

或者也许有更好的方法,或者我对解析接口的理解是错误的。

编辑: 提供一个例子,我的代码目前是如何工作的: 在服务文件中:

getTiers () {
      return this.http.get(this.authService.getApiEndpoint(), this.authService.getRequestOptions())
      .map(
        (response: Response) => {
          const data = response.json();
          return data;
        }
      );

在我的组件文件中: ngOnInit() { this.getTiers();

}

  getTiers () {
    this.tierService.getTiers()
      .subscribe(
        (tiers) =>
          this.tiers = tiers.data,
        (error) => console.log(error),
        () => this.initializingCompleted = true
      );
  }

在我的模板文件中:

    <div class="col-md-4" *ngFor="let tier of tiers">
        <ul class="table">
          <li class="title">
            {{ tier.title }}
          </li>
[...]

异步加载数据是使用 Angular 的好处之一。因为它是一个单页应用程序,所以在加载着陆页时,如果您适当地使用异步方法,将有助于您解决这个问题。看看这篇文章https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components

祝你好运

使用整个应用程序都可用的服务来加载数据并将其存储在 rxjs BehaviorSubject 中。

public data$: BehaviorSubject<any> = new BehaviorSubject(null);

constructor(private http: Http){
  this.http.get(...).map(...).subscribe(res => this.data$.next(res))
}

然后从您的组件:

public data: any;

constructor(private myService: MyService){
  this.data = this.myService.data$.value;
  this.myService.data$.subscribe(res => this.data = res);
}

注意:如果需要重新设置行为主体的值data$.next(null)