2

I want to transform keys to value(fetched from server using server call).

View

<div> {{ 'SomeText1' | performtranslation }} </div>
<div> {{ 'SomeText2' | performtranslation }} </div>

Pipe definition

transform(key: string): string {
    //http server call 
    var updatedValue = http.get(key); //Just example
    return updatedValue ;
}

Since here we have two translations, call to server is made twice. Likewise if 100 keys are there, 100 calls will be made. How can we restrict and do a single call.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
user1853803
  • 649
  • 3
  • 8
  • 27

1 Answers1

0

You can use a service (singleton) where you cache the results and return them immediately when found in cache instead of calling to the server. See also What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • For second time we can cache it but on first time load 100 calls would be made. Any idea to restrict it or optimize it. – user1853803 Dec 01 '16 at 10:28
  • My answer in the linked question should prevent exactly that. Not sure about the others. – Günter Zöchbauer Dec 01 '16 at 10:29
  • And what about make 1 call that returns an array ? – soywod Dec 01 '16 at 10:30
  • Caching I understood but even for first time, I need a solution. In certain cases, it can be 200-400 keys. – user1853803 Dec 01 '16 at 10:30
  • I don't get what the problem is. You want to combine all keys into a single request instead of one request per key? In this case you need to specify when the request should be made. You can queue the keys in the service and when the service gets the signal, can send the request for all keys. – Günter Zöchbauer Dec 01 '16 at 10:32
  • Agreed. My all the keys are their in view(html page). I need to pick from there. I cannot key it in component definitions. – user1853803 Dec 01 '16 at 10:34
  • It's a bit complicated because you need to remember what key was requested by what call. I think the approach in my linked answer should get you started. I don't plan to develop a ready-to-use solution for you. That's to broad. – Günter Zöchbauer Dec 01 '16 at 10:40