5

The code below is a simplified version of what I currently have:

name.service.ts

@Injectable() export class NameService { const nameURL = "http://www.example.com/name"; getName() { return this.http.get(nameURL); } } 

name1.component.ts

@Component({ templateUrl: './name1.component.html', styleUrls: ['./name1.component.css'] }) export class Name1Component implmenets OnInit { private name1; constructor( private nameService: NameService ){} ngOnInit() { this.setupName(); } private setupName() { this.nameService.getName() .subscribe( resp => this.name1 = resp, error => this.name1 = "unknown" ); } } 

name2.component.ts

@Component({ templateUrl: './name2.component.html', styleUrls: ['./name2.component.css'] }) export class Name2Component implmenets OnInit { private name2; constructor( private nameService: NameService ){} ngOnInit() { this.setupName(); } private setupName() { this.nameService.getName() .subscribe( resp => this.name2 = resp, error => this.name2 = "unknown" ); } } 

Here is what I want to do, name1.component.ts will first call the getName method of the NameService class. getName will then make an ajax call and return an observable.

Next, name2.component.ts will also call the same getName method of the NameService class, and getName will also perform the same ajax call and return an observable.

Is it possible using rxjs whereby when getName method in NameService makes its first ajax call, it then stores the result of the ajax call. Any subsequent function calls to the getName method will instead return the cache result of the first ajax call and not perform another redundant ajax.

6
  • try saving these value in localstorage of the browser. First check localstorage if values did'nt exist make a call to server else retrieve it from localstorage and use it Commented Jan 9, 2017 at 15:28
  • You can. Here is the link: syntaxsuccess.com/viewarticle/… Commented Jan 9, 2017 at 15:28
  • @rashfmnb I would prefer a rxjs solution. Commented Jan 9, 2017 at 17:01
  • @IgorJanković I read the link you shared and tried implementing it in my code. But it doesn't work. I still see 2 network requests being made in the browser as opposed to one. Commented Jan 9, 2017 at 17:01
  • check this answer stackoverflow.com/questions/36271899/… Commented Jan 9, 2017 at 17:57

1 Answer 1

4

You can subscribe to the Observable multiple times, so if all you want to do is save the second network request for data shared between two Components, you can cache it in your Service like this:

@Injectable() export class NameService { const nameURL = "http://www.example.com/name"; private cache: Observable<any>; getName() { return this.cache || this.cache = this.http.get(nameURL); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.