Angular2 : Reduce number of Http calls

独自空忆成欢 提交于 2019-12-11 06:37:32

问题


I'm using Angular2 RC5 with an ASP.NET Core server that makes the API calls to get my data. I'm actually wondering if there is a way to reduce the number of http calls you make with Angular2, because I fear there will be a lot if I keep using components the way I do. Here is a concrete example.

I want to get a text value from the database, which is defined by an ID and a Language. I then made the following component :

dico.component.ts

@Component({
    selector: 'dico',
    template: `{{text}}`,
    providers: [EntitiesService]
})

class Dico implements AfterViewInit {
    @Input() private id: string;   
    @Input() private lang: string;
    private text: string = null;

    // DI for my service
    constructor(private entitiesService: EntitiesService) {
    }

    ngAfterViewInit() {
        this.getDico();
    }

    // Call the service that makes the http call to my ASP Controller
    getDico() {
        this.entitiesService.getDico(this.id, this.lang)
            .subscribe(
            DicoText => this.text = DicoText
            );
    }
}

@Component({
    template: `<dico [id] [lang]></dico>`,
    directives: [Dico]
})

export class DicoComponent {
}

Here is the code from my service :

entities.service.ts

getDico(aDicoID: string, aLangue: string) {
        // Parameters to use in my controller
        let params = new URLSearchParams();
        params.set("aDicoID", aDicoID);
        params.set("aLangue", aLangue);
        // Setting up the Http request
        let lHttpRequestBody = params.toString();
        let lControllerAction: string = "/libelle";
        let lControllerFullURL: string = this.controllerURL + lControllerAction;
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(lControllerFullURL, lHttpRequestBody, options)
            .map((res: any) => {
                // Parsing the data from the response
                let data = res.json();

                // Managing the error cases
                switch (data.status) {
                    case "success":
                        let l_cRet: string = data.results;
                        if (l_cRet != null && !l_cRet.includes("UNDEFINED")) {
                            return data.results;
                        } else {
                            throw new Error("Erreur récupération Dico : " + l_cRet);
                        }
                    case "error":
                        throw new Error("Erreur récupération Dico : " + data.message);
                }
            }
            ).catch(this.handleError);
}

Then I can use my newly made component in my app :

randomFile.html

<dico id="201124" lang="it"></dico>
<dico id="201125" lang="en"></dico>
<dico id="201126" lang="fr"></dico>

But this application will eventually use hundreds of these "dico" and I was wondering how I could manage some pre-fetch or something like that before the app fully loads. Does it even matter ? Will that affect performance in the long term ?

Any advice would be greatly appreciated.

EDIT : These dico allow me to fetch from the database a text translated into the langage I want. Here, in the example above, I have 3 "dico" that will output some text in italian, french, and english. My application will use a lot of them, as every text in every menu will be a "dico", and the problem is that there will be a lot of them, and right now for every "dico" I make, my service is called and makes one http call to get the data. What I want is to somehow define all my dicos, call the service which will give me the text of all my dicos in an array to avoid making several calls (but I don't really know how to do that).


回答1:


A basic untested approach (I don't know observables too well myself)

class DicoService {
  private subjects = {}
  private ids = [];

  getDico(String id):Observable<Dico> {
    var s = this.subjects[id];

    if(!s) {
      this.ids.push(id);
      s = new Subject(); 
      this.subjects[id]=s;
    }
    return s.asObservable().share().first();
  }

  sendRequest() {
    http.get(....) /* pass this.ids */
    map(response => response.json())
    .subscribe(data => {
      for(item in data) { // don't know how to iterate exactly because I don't know how the response will look like
        this.subject[item.id].next(item.langText);
      }
      // you might cache them if other components added by the router also request them
      // this.subjects = {};
      // this.ids = []
    });
  }  
}
<dico [text]="dicoService.getDico('someId') | async"></dico>
ngAfterViewInit() {
  this.dicoService.sendRequest();
}


来源:https://stackoverflow.com/questions/39345083/angular2-reduce-number-of-http-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!