在后台从 API 加载数据

jun*_*_dn 1 javascript angular2-routing angular

我目前正在努力改善我的用户体验。当用户切换到新组件时,大约需要 0.5 到 1 秒的时间才能加载数据并显示在视图中。因此,在最初的时刻,视图是空的,某些部分丢失或显示错误。

我知道有角度解析接口。然而,据我了解,这只是延迟视图的渲染,直到数据可用。

我想知道是否有一个选项,您可以在渲染我的应用程序的登陆页面后在后台加载数据。这样,用户就可以在后台使用和查看应用程序,而不会注意到正在加载其他页面/组件的数据。

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

编辑: 提供一个示例,说明我的代码当前如何工作:在服务文件中:

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

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

}

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

在我的模板文件中:

    <div class="col-md-4" *ngFor="let tier of tiers">
        <ul class="table">
          <li class="title">
            {{ tier.title }}
          </li>
[...]
Run Code Online (Sandbox Code Playgroud)

Plo*_*ppy 5

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

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

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

然后从你的组件:

public data: any;

constructor(private myService: MyService){
  this.data = this.myService.data$.value;
  this.myService.data$.subscribe(res => this.data = res);
}
Run Code Online (Sandbox Code Playgroud)

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