MadCatm2
MadCatm2

Reputation: 1001

Different JSON response with same request

In my Angular application service I have a method that makes a call to a mock JSON:

my.service.ts:

 ...
 private baseUrl: string = 'http://localhost:9999/accounts-grid.json';
 ...

    loadAccounts() {

            if (this.dataStore.responseObject) {
                this.refreshDataStore();
            }
            let token = this.authenticationService.getToken();
            let headers = new Headers({ 'netx.esf.AuthenticationService': token });
            let options = new RequestOptions({ headers: headers });

  this.http.get(`${this.baseUrl}/positions/priorday/${accountNumber}`, options)
            this.http.get(`${this.baseUrl}`, options)
                .map((response: Response) => response.json())
                .subscribe(
                ...
                error => {
                    this.logService.error('loadAccountList() exception:', error);
                this.setError(this.message[0], error._body);         });

        return this.responseObject$;
}

I would like to be able to load a different dummy JSON with the same call depending how many times the method was called. For example, the first time I call loadAccounts(), I would like to get a response from accounts-grid.json, the second time I make this call I would like to get a response from, say, accounts2-grid.json.

Is this possible?

Upvotes: 1

Views: 88

Answers (1)

Z. Bagley
Z. Bagley

Reputation: 9270

Add a local variable to the service to keep track:

 ...
 private baseUrl: string = 'http://localhost:9999/accounts-grid.json';
 private callCount = 0;
 ...

    loadAccounts() {
            if ( this.callCount > 0 ) { const newUrl = this.baseUrl.substring(0, this.baseUrl.lastIndexOf('.json')) + this.callCount.toString() + this.baseUrl.substring(this.baseUrl.lastIndexOf('.json')); }
            this.callCount += 1;


            if (this.dataStore.responseObject) {
                this.refreshDataStore();
            }
            let token = this.authenticationService.getToken();
            let headers = new Headers({ 'netx.esf.AuthenticationService': token });
            let options = new RequestOptions({ headers: headers });

  this.http.get(`${newUrl}/positions/priorday/${accountNumber}`, options)
            this.http.get(`${newUrl}`, options)
                .map((response: Response) => response.json())
                .subscribe(
                ...
                error => {
                    this.logService.error('loadAccountList() exception:', error);
                this.setError(this.message[0], error._body);         });
        return this.responseObject$;
}

You will probably also want to take care of the callCount item to subtract a count if there's an error, but this is the general idea.

Upvotes: 2

Related Questions