Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS 5 Observable and Angular2 http: Call ajax once, save the result, and subsequent ajax calls use cached result

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.

like image 544
Thanesh R Avatar asked Jan 09 '17 15:01

Thanesh R


1 Answers

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);
    }
}
like image 162
Nuvanda Avatar answered Oct 21 '22 09:10

Nuvanda