在我的Angular应用程序服务中,我有一个方法可以调用模拟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$;
}
我希望能够根据调用方法的次数加载具有相同调用的不同虚拟JSON。例如,我第一次调用loadAccounts()时,我想从accounts-grid.json获得响应,第二次进行此调用时,我想从accounts2-grid.json获得响应。
这可能吗?
答案 0 :(得分:2)
向服务添加本地变量以跟踪:
...
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$;
}
如果出现错误,您可能还需要处理callCount项以减去计数,但这是一般的想法。