首页 > 解决方案 > 在 ExtJS 中使用 Rest URL 中的 DataFields 来访问 Context.io API

问题描述

我有两个关于 EXTJS 中的 Rest API 的问题。

  1. 如何使用字段来使 REST URL 动态化?
  2. 如何在我的 Rest.Proxy 中添加身份验证密钥以访问 Context.io?

这是我的解决方案,但我不确定我是否做得正确。我是 ExtJS 的新手,所以我的问题可能是基本的,但我感谢您的帮助。

Ext.define("EmailFolders", {
  extend: "Ext.data.Model",
  fields: ["id", "label"],

  proxy: {
    type: "rest",
    url: "lite/users/:" + id + "/email_accounts/:" + label + "/folders"
  },

  reader: {
    type: "json"
  },

  headers: {
    CONSUMER_KEY: "KEY FROM CONTEX.IO",
    CONSUMER_SECRET: "SECRET FROM CONTEXT.IO"
  }
});

标签: restextjsfield

解决方案


您可以使用store.getProxy()使 REST URL 动态化并在标头中传递身份验证密钥。代理有方法

  1. proxy.setUrl()设置 url 的值。
  2. proxy.setHeaders()设置标题的值。

你可以在这里检查工作小提琴

代码片段

Ext.application({
    name: 'Fiddle',

    launch: function () {
        let url = 'https://jsonplaceholder.typicode.com/users';
        // Set up a model to use in our Store
        Ext.define('User', {
            extend: 'Ext.data.Model',

            proxy: {
                type: 'ajax',
                reader: {
                    type: 'json',
                    rootProperty: ''
                }
            }

        });

        Ext.define('MyStore', {
            extend: 'Ext.data.Store',
            model: 'User',

            listeners: {
                beforeload: function (store) {
                    var proxy = store.getProxy();

                    //if you want, you can also set here url inside of beforeload
                    //proxy.setUrl(url);

                    /*
                     * You can use {proxy.setHeaders} to set the values from CONTEX.IO
                     * After ajax request see your request parameter in network analysis below 2 headers are passed in request header
                     */
                    proxy.setHeaders({
                        CONSUMER_KEY: "KEY FROM CONTEX.IO",
                        CONSUMER_SECRET: "SECRET FROM CONTEXT.IO"
                    });

                }
            }
        });

        let store = new MyStore();
        //Set the dynamic url here
        //This {url} will be dynamic whatever you want to pass
        store.getProxy().setUrl(url);

        store.load(function (data) {
            console.log(data);
            alert('Open console to see reposne..!')
        });

        /*
         You can also pass url inside of load funtion
        */
        new MyStore().load({
            url: url + '/' + 1,
            callback: function (data) {
                console.log(data);
            }
        });
    }
});

推荐阅读