Angular2 - 使组件等待,直到服务完成获取数据,然后呈现它

时间:2017-02-12 22:14:04

标签: javascript ajax angular typescript

我无法实现一次加载数据(gyms数组)的服务,然后允许所有其他组件使用它,而不会发出其他HTTP请求。

如果用户在标题页面开始并加载了所有数据,我的应用程序工作正常,但是当我转到特定的详细信息页面(... / gym / 1)并重新加载页面时,该对象不是在服务阵列中。如何使尝试访问服务数组的组件等到数据加载完毕?更具体地说,如何在GymComponent中延迟对gymService.getGym(1)的调用,直到填充数组的getAllGymsFromBackEnd()函数完成?

我已经阅读过有关旋转变压器的信息,但我的修补工作让我无处可去。

任何帮助都将不胜感激。

这是我正在处理的代码:

服务:

import {Injectable} from "@angular/core";
import {Gym} from "../objects/gym";
import {BaseService} from "./base.service";
import {Http, Response} from "@angular/http";
import {HttpConstants} from "../utility/http.constants";

@Injectable()
export class GymService extends BaseService {

   private gyms: Gym[] = [];

   constructor(protected http: Http, protected httpConstants: HttpConstants) {
      super(http, httpConstants);
      this.getAllGymsFromBackEnd();
   }

   getAllGymsFromBackEnd() {
      return super.get(this.httpConstants.gymsUrl).subscribe(
         (data: Response) => {
            for (let gymObject of data['gyms']) {
               this.gyms.push(<Gym>gymObject);
            }
         }
      );
   }

   getGyms() {
      return this.gyms;
   }

   getGym(id: number) {
      return this.gyms.find(
         gym => gym.id === id
      )
   }
}

组件:

import {Component, OnDestroy, AfterViewInit, OnInit} from "@angular/core";
import {ActivatedRoute} from "@angular/router";
import {Subscription} from "rxjs";
import {Gym} from "../../objects/gym";
import {GymService} from "../../services/gym.service";
declare var $:any;

@Component({
   selector: 'app-gym',
   templateUrl: './gym.component.html',
   styleUrls: ['./gym.component.css']
})
export class GymComponent implements OnInit, OnDestroy, AfterViewInit {

   private subscription: Subscription;
   private gym: Gym;

   constructor(private activatedRoute: ActivatedRoute,
            private gymService: GymService
   ) {}

   ngOnInit(): void {
      this.subscription = this.activatedRoute.params.subscribe(
         (param: any) => {
            this.gym = this.gymService.getGym(parseInt(param['id']));
         }
      );
   }

   ngAfterViewInit(): void {
      $( document ).ready(function() {
         $('.carousel').carousel();
      });
   }

   ngOnDestroy(): void {
      this.subscription.unsubscribe();
   }
}

1 个答案:

答案 0 :(得分:1)

您也可以使用foo。在这里查看https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html或使用Observable。因此Resolver将变为private gym: Gym;,并在您的模板中使用private gym$:Observable<Gym>;管道获取数据。