Nativescript Core ListView使用JSON数据/对象获取

时间:2019-07-08 01:19:33

标签: javascript listview mvvm telerik nativescript

我整整一天的大部分时间都在浏览该网站以及其余的内部网络,这些东西可能对您所有的顶级狗来说都是不费吹灰之力的。我没有发现所有内容都包含在内,并且总体上大多数样本都缺少一定程度的清晰度。

所以我想尝试完成MVVM模式,仅从Web服务获取JSON结果并填充列表视图:)

网络服务返回此信息

[{"total_bulls":"651","GenericName":"Aripiprazole","brandName":"Abilify","drugCat":"Atypical Antipsychotic","bullID":2793,"fastURL":"http:\/\/got*****.com\/drug-bulletin\/abilify\/","litAlertLvl":"High"},{"total_bulls":"651","GenericName":"Zafirlukast","brandName":"Accolate","drugCat":"Leukotriene Antagonist","bullID":2794,"fastURL":"http:\/\/got****.com\/drug-bulletin\/accolate\/","litAlertLvl":"Withdrawn"},{"total_bulls":"651","GenericName":"Albuterol Sulfate Inhalation Solution","brandName":"AccuNeb","drugCat":"Bronchodilator","bullID":2855,"fastURL":"http:\/\/go***.com\/drug-bulletin\/accuneb\/","litAlertLvl":"Low"},{"total_bulls":"651","GenericName":"Quinapril Hydrochloride","brandName":"Accupril","drugCat":"ACE Inhibitor","bullID":2661,"fastURL":"http:\/\/go****.com\/drug-bulletin\/accupril\/","litAlertLvl":"Low"},{"total_bulls":"651","GenericName":"Quinapril HCl\/Hydrochlorothiazide","brandName":"Accuretic","drugCat":"ACE Inhibitor\/Thiazide Diuretic","bullID":2813,"fastURL":"http:\/\/got****.com\/drug-bulletin\/accuretic\/","litAlertLvl":"High"}]

我希望ListView显示正确的数据并触发单击动作。我遇到了很多问题,无法从调用Web服务以填充列表视图的结果中获取结果。

我可以这样手动填充模型:

const viewModel = observableModule.fromObject({

    bulletins: []

    // Setting the listview binding source
    /*
    bulletins: [
        {
            "total_bulls": "651",
            "GenericName": "Aripiprazole",
            "brandName": "Abilify",
            "drugCat": "Atypical Antipsychotic",
            "bullID": 2793,
            "fastURL": "http://g****s.com/drug-bulletin/abilify/",
            "litAlertLvl": "High"
          }, {
            "total_bulls": "651",
            "GenericName": "Zafirlukast",
            "brandName": "Accolate",
            "drugCat": "Leukotriene Antagonist",
            "bullID": 2794,
            "fastURL": "http://g****.com/drug-bulletin/accolate/",
            "litAlertLvl": "Withdrawn"
          }, {
            "total_bulls": "651",
            "GenericName": "Albuterol Sulfate Inhalation Solution",
            "brandName": "AccuNeb",
            "drugCat": "Bronchodilator",
            "bullID": 2855,
            "fastURL": "http://go****.com/drug-bulletin/accuneb/",
            "litAlertLvl": "Low"
          }
    ]
    */

});

但是,尝试使用该调用的JSON结果来实现这一点非常困难。

1 个答案:

答案 0 :(得分:0)

经过数小时的反复试验,我得出了这种工作模式。欢迎对此进行改进。

从Sidekick或从https://market.nativescript.org/plugins/tns-template-drawer-navigation处启动香草JS Core Nativescript“抽屉导航”模板项目,然后添加这些脚本(我将前三个放在名为“ bulletins”的文件夹中,最后一个放在一个名为“服务”的文件夹。)

我还添加了列表视图插件。

bulletins-page.xml

<Page class="page" navigatingTo="onNavigatingTo" 
    xmlns="http://schemas.nativescript.org/tns.xsd">

    <ActionBar class="action-bar">
        <!-- 
        Use the NavigationButton as a side-drawer button in Android
        because ActionItems are shown on the right side of the ActionBar
        -->
        <NavigationButton ios:visibility="collapsed" icon="res://menu" tap="onDrawerButtonTap"></NavigationButton>
        <!-- 
        Use the ActionItem for IOS with position set to left. Using the
        NavigationButton as a side-drawer button in iOS is not possible,
        because its function is to always navigate back in the application.
        -->
        <ActionItem icon="res://navigation/menu" android:visibility="collapsed" tap="onDrawerButtonTap" ios.position="left">
        </ActionItem>
        <Label class="action-bar-title" text="Bulletins"></Label>
    </ActionBar>

    <GridLayout class="page-content">
        <Label class="page-icon fa" text="&#xf005;"></Label>
        <Label class="page-placeholder" text="<!-- Page content goes here -->"></Label>
    </GridLayout>

    <ScrollView>
        <StackLayout>
            <ListView items="{{ bulletins }}" itemTap="onItemTap" loaded="{{ onListViewLoaded }}" 
            separatorColor="orangered" rowHeight="100" height="500" class="list-group" id="listView" row="2">
                <ListView.itemTemplate> 
                    <!-- The item template can only have a single root view container (e.g. GriLayout, StackLayout, etc.) -->
                    <StackLayout class="list-group-item">
                        <Label text="{{ GenericName || 'Downloading...' }}" textWrap="true" class="title" />
                        <Label text="{{ brandName || 'Downloading...' }}" textWrap="true" class="title" />
                    </StackLayout>
                </ListView.itemTemplate>
            </ListView>>
        </StackLayout>
    </ScrollView>
</Page>

bulletins-page.js

const app = require("tns-core-modules/application");
const BulletinsViewModel = require("./bulletins-view-model");
const listViewModule = require("tns-core-modules/ui/list-view");

function onNavigatingTo(args) {
    const page = args.object;
    //bind the page to this the viewModel Function
    page.bindingContext = new BulletinsViewModel();
    //now call the function that GETS the data from the API AFTER the model is declared
    BulletinsViewModel.showBulletins()
}
exports.onNavigatingTo = onNavigatingTo;

function onListViewLoaded(args) {
    const listView = args.object;
}
exports.onListViewLoaded = onListViewLoaded;

function onItemTap(args) {
    const index = args.index;
    console.log(`Second ListView item tap ${index}`);
}
exports.onItemTap = onItemTap;

function onDrawerButtonTap(args) {
    const sideDrawer = app.getRootView();
    sideDrawer.showDrawer();
}
exports.onDrawerButtonTap = onDrawerButtonTap;

bulletins-view-model.js

const observableModule = require("tns-core-modules/data/observable");
const SelectedPageService = require("../shared/selected-page-service");
const bulletinService = require("~/services/bulletin-service");

function BulletinsViewModel() {
    SelectedPageService.getInstance().updateSelectedPage("Bulletins");

    //declare the viewmodel
    const viewModel = observableModule.fromObject({
        //declare the properties of this viewmodel
        bulletins: []

    });

    //declare a function to be called LATER during the navigation to the view
    BulletinsViewModel.showBulletins = function () {
        //call the fetch function and pass it the users info
        bulletinService.allBulletins({
            user: 'admin',
            password: this.password
        }).then((r) => {
            console.log(r);
            //pass the response to the properties of the model
            viewModel.bulletins = r;
        })
            .catch((e) => {
                console.log(e);
                alert("Unfortunately we could not find any bulletins");
            });
    }

    return viewModel;
}

module.exports = BulletinsViewModel;

bulletin-service.js

exports.allBulletins = function () {
    return new Promise((resolve, reject) => {
        fetch("https://got****.com/wp-admin/admin-ajax.php?action=all-bulletins-paged")
            .then((response) => response.json())
            .then((r) => {
                if (r.total_bulls == 0) {
                    //console.log('No Bulletins Found' + r.total_bulls);
                    reject(r);
                }
                //console.log('JSON Bulletins Found' + JSON.stringify(r));
                resolve(r);
            }).catch((err) => {
                console.log(err);
                reject(err);
            });
    });
};