【问题标题】:Different JSON response with same request具有相同请求的不同 JSON 响应
【发布时间】:2017-10-04 19:18:31
【问题描述】:

在我的 Angular 应用程序服务中,我有一个调用模拟 JSON 的方法:

我的.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 获得响应。

这可能吗?

【问题讨论】:

    标签: javascript json angular


    【解决方案1】:

    给服务添加一个局部变量来跟踪:

     ...
     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 项以减去计数,但这是一般的想法。

    【讨论】:

    • 好的,我理解这个的主旨,但新字符串的结果将是“account-list.json1”,而不是“account-list1.json”,我相信这将是一个sys.js 的问题。知道如何解决这个问题吗?
    • 您可以使用substring()lastIndexOf() 来解决这个问题。我更新了分析器以反映。
    • 你是个天才。
    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 2019-12-09
    • 1970-01-01
    • 2018-09-24
    • 2014-09-10
    • 2019-05-07
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多