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.