2015-09-30 15 views
1

我在我的Ember應用程序中使用標準ActiveModelAdapter來完成我的大部分查詢以使用Ember模型對象。然而,在一種情況下,我想製作一個任意的REST請求來取回JSON來填充圖表(不是由模型支持),但是我想通過ActiveModelAdapter「去」,以便使用正確的主機值。使用ActiveModelAdapter在燼中創建任意JSON查詢

這裏有什麼不工作:

updateChartFromIndustry: function() { 
    Ember.$.ajax({ 
    context: this, 
    method: 'get', 
    url: 'api/v3/charts/all_risk.json', 
    dataType: 'json', 
    data: { ind: this.get('ind') } 
    }).then(function(json) { 
     Ember.$('#risk-days-data').highcharts(json); 
    }, 
    function(errs) { 
     console.log(errs); 
    } 
); 
}.observes('ind'), 

在發展中,該查詢去到localhost:4200(餘燼服務器),而不是本地主機導軌後端:3000。明確設置完整的URL會使查詢通過,但沒有驗證請求的各種用戶會話信息。

我真的希望能爲喜歡簡單的東西:

this.store.query('arbitrary url and params', ....) 

,如果我做了一個正常的查詢模型或交替,以利用適配器:

Ember.adapter.$.ajax(....) 
+1

我認爲你要麼用一個基本的模型支持圖表,要麼在你的ajax調用中包含你需要的任何認證內容。 –

+0

回想起來,我認爲這是正確的答案。建立一個圖表模型。我仍然可以這樣做,但目前的黑客攻擊是低於。 – GSP

回答

2

我發佈此爲「一種」的方式來做到這一點,不一定是正確的方式來做到這一點。

簡短的回答是,適配器可用(即使在組件中)通過this.container.lookup('adapter:application')。它可以用來直接發送AJAX查詢。我認爲你可以設置你自己的適配器並覆蓋默認行爲,但在這種情況下,我可以用我想使用默認適配器的方式欺騙​​它。

updateChartFromIndustry: function() { 
    let adapter = this.container.lookup('adapter:application'); 

    // create the URL. Not that the 'chart' is, by default, pluralized to "charts". 
    // This happened to be good for my API. 
    // The second parameter becomes the "id" which I use to identify 
    // the chart name. 
    // http://localhost:3000/api/v3/charts/all_risk 
    let url = adapter.buildURL('chart', 'all_risk'); 

    // object.data is automatically converted into query params 
    let params = { data: { ind: this.get('ind') } }; 

    // make the GET request and build the Chart with the response 
    adapter.ajax(url, 'GET', params).then(function(response) { 
    Ember.$('#my-chart').highcharts(response); 
    }); 
}.observes('ind'), 

P.S.這是用ActiveModelAdapter完成的,但是從DS.RESTAdapter派生的任何東西都應該允許相同的行爲。

0

你可能需要添加代理標誌啓動服務器時:

ember server Starts the server. The default port is 4200. Use the --proxy flag to proxy all ajax requests to the given address. For example, ember server --proxy http://127.0.0.1:8080 will proxy all ajax requests to the server running at http://127.0.0.1:8080.

http://www.ember-cli.com/user-guide/#using-ember-cli