如何正确绑定异步。将新闻 API 中的数据加载到视图并将数据显示为内容?

How to proper bind async. loaded data from a news API to a view and display the data as content?

我想从新闻 API (https://newsapi.org/) in my SAPUI5 application like done here (https://www.nathanhand.co.uk/blog/post/creating-a-news-app-using-ui5) 获取数据,但没有 express 和 Node.js。获取过程本身有效,我从 JSON 中的 API 获取了数据。问题似乎是 UI5 的生命周期,尤其是 API 数据的异步加载。我目前无法在我的视图中显示数据,因为它到达晚了,它似乎已经用视图初始化了。

我已尝试使用 "attachRequestCompleted" 事件处理程序,以确保数据存在并且仅在数据到达时才采取进一步的操作。但这并没有解决问题,数据已正确绑定到视图,但似乎为时已晚。

return Controller.extend("newsapitest.newsapitest.controller.View1", {
    onInit: function () {
        var thisContext = this;

        var articleModel = new JSONModel("https://newsapi.org/v2/top-headlines?country=DE&category=business&apiKey=*********");

        articleModel.attachRequestCompleted(function(oEvt) {
             var model = oEvt.getSource();
             thisContext.getView().setModel(model, "articles");
        });
    }
});


<content>
    <GenericTile backgroundImage="{articles>/1/urlToImage}"
    frameType="TwoByOne" press="onArticlePress">
        <TileContent footer="{articles>/1/publishedAt}">
            <NewsContent contentText="{articles>/1/title}" 
            subheader="{articles>/1/description}" />
        </TileContent>
     </GenericTile>
</content>

所以我希望我视图中的图块会显示存储在模型中的每篇文章的信息。但目前只有一个空磁贴,那里没有显示任何数据。

解决方案 我在将模型绑定到我的控件时犯了一个错误。那是一个错误。我更改的另一件事是如何将数据加载到我的模型中。

return Controller.extend("newsapitest.newsapitest.controller.View1", {
    onInit: function () {
        var articleModel = new JSONModel();
        articleModel.loadData("https://newsapi.org/v2/top-headlines?country=DE&category=business&apiKey=37a02aae93684d58810e0b996954f534");
        this.getView().setModel(articleModel);
    },
});

<content>
                  <GenericTile
                        backgroundImage="{/articles/0/urlToImage}"
                        frameType="TwoByOne" press="onArticlePress">
                    <TileContent footer="{/articles/0/publishedAt}">
                        <NewsContent
                                contentText="{/articles/0/title}"
                                subheader="{/articles/0/description}" />
                    </TileContent>
                </GenericTile>
            </content>

您检查过您的绑定路径是否正确吗?无论如何,您进行绑定的方式只会创建一个磁贴,其中的信息存储在文章数组的第二个位置(位置 1)。

如果您想根据数组的位置数动态创建多个图块,我认为您不能使用 "Generic Tile" 组件,而是可以使用 "Tile Container" 如下(这是一个已弃用的组件,但我认为没有其他方法可以这样做,至少在视图上):

<TileContainer
            tiles="{articles>/}">
            <StandardTile
                title="{articles>title}"
                info="{articles>publishedAt}"
                infoState="{articles>description}" />
</TileContainer>

如果其他人知道一种不使用已弃用组件的方法,那就太好了:)。