代码之家  ›  专栏  ›  技术社区  ›  ristapk

本机脚本获取和显示

  •  0
  • ristapk  · 技术社区  · 8 年前

    我需要一个使用nativescript的最简单的获取和显示示例如果有人有github回购协议,我将不胜感激。 谢谢 实际上,我想读取一个JSON并在本地脚本的列表中显示数据。

    2 回复  |  直到 8 年前
        1
  •  4
  •   Nick Iliev    8 年前

    Vey基本示例 in this Playground -在主要的NativeScript文档中,也有很多关于这两者的示例 fetch data binding

    基本上,您可以使用 Observable 并将其绑定到XML视图(以上所有内容都与NativeScript核心相关-请参阅 this for NativeScript Angula (右图)

    import { EventData, Observable, fromObject } from 'tns-core-modules/data/observable';
    import { StackLayout } from 'tns-core-modules/ui/layouts/stack-layout';
    
    // Event handler for Page "pageLoaded" event attached in home-page.xml
    export function pageLoaded(args: EventData) {
    
        let page = <StackLayout>args.object;
    
        let viewModel = new Observable();
        viewModel.set("items", [])
    
        fetch("https://httpbin.org/json")
            .then((response) => response.json())
            .then((res) => {
                // console.log(res.slideshow.slides[1].items);
                viewModel.set("items", res.slideshow.slides[1].items);
            }).catch((err) => {
        });
    
        page.bindingContext = viewModel;
    }
    

    以及列表视图,以XML格式呈现列表

    <ListView class="list-group" items="{{ items }}" itemTap="{{ onItemTap }}" style="height:1250px">
        <ListView.itemTemplate>
            <FlexboxLayout flexDirection="row" class="list-group-item">
                <Label text="{{ $value }}" />
            </FlexboxLayout>
        </ListView.itemTemplate>
    </ListView>
    

    当然,上面是一个非常简单的示例,它将值直接作为字符串数组接收有关数据绑定的更多选项,请检查 this documentation article

        2
  •  1
  •   Samuel    8 年前

    如果我想从中获取数据,可以分享一段代码片段吗? https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey= {API_KEY}我的数据是垂直显示的

    CBS显示如下:

    C类

    S公司

    fetch("https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8f65d5e676e44da89848f43ed0******")
    		.then((response) => response.json())
    		.then((res) => {
    			//console.log(res.slideshow.slides[1].items);
    			//viewModel.set("items", res.slideshow.slides[1].items);
    			console.log("title: ", res.articles[3].title);
    			viewModel.set("title", res.articles[3].title);
    		}).catch((err) => {
    		});

    谢谢你@Nick Liev