http getJSON в Nativescript - PullRequest
       1

http getJSON в Nativescript

0 голосов
/ 05 декабря 2018

Я скачал новостную ленту с изображениями и текстовыми элементами Приложение Nativescript локально и пытаюсь заставить его работать с прямой трансляцией с newsapi.org.

Исходное приложение имеет код jsonвот так:

allNews: { source: Source, author: string, title: string, description: string, url: string, urlToImage: string, publishedAt: string }[] = [{ "source": { "id": null, "name": "Yahoo.com" }, "author": null, "title": "The Latest: Russia says no evidence of gas attack in Douma", "description": null, "url": "https://www.yahoo.com/news/latest-turkey-urges-sides-avoid-more-syria-turmoil-113652213.html", "urlToImage": null, "publishedAt": "2018-04-13T19:44:00Z" }, { "source": { "id": "the-washington-post", "name": "The Washington Post" }, "author": "http://www.facebook.com/matt.zapotosky", "title": "Trump issues pardon to 'Scooter' Libby, former chief of staff to Vice President Cheney", "description": "The Bush administration aide was convicted of perjury before a grand jury, lying to FBI investigators and obstruction of justice.", "url": "https://www.washingtonpost.com/politics/trump-issues-pardon-to-scooter-libby-former-chief-of-staff-to-vice-president-cheney/2018/04/13/dfa4039a-3f2d-11e8-8d53-eba0ed2371cc_story.html", "urlToImage": "https://www.washingtonpost.com/rf/image_1484w/2010-2019/WashingtonPost/2018/04/13/National-Politics/Images/AFP_13Z4QQ.jpg?t=20170517", "publishedAt": "2018-04-13T19:06:25Z" }, { "source": { "id": "the-new-york-times", "name": "The New York Times" }, "author": "", "title": "Where's the Boom in Bank Lending?: DealBook Briefing", "description": "Bank lending was expected to surge this year. But going by bank results so far, lending in the first quarter is set to disappoint.", "url": "https://www.nytimes.com/2018/04/13/business/dealbook/trump-trans-pacific-partnership.html", "urlToImage": "https://static01.nyt.com/images/2018/02/03/us/14db-newsletter-wells/14db-newsletter-wells-facebookJumbo-v2.jpg", "publishedAt": "2018-04-13T18:56:00Z" }];

Внутри моего app/home/home-view-model.ts Я добавил:

import { getJSON } from "tns-core-modules/http";
...

   allNews: { source: Source,
               author: string,
               title: string, 
               description: string, 
               url: string, 
               urlToImage: string, 
               publishedAt: string 
            }[] = getJSON("newsapi link").then((r: any) => {
            }, (e) => {
            });
             ;

Я делаю это на основе документации здесь: https://docs.nativescript.org/ns-framework-modules/http. Однако, получаю ошибку:

app/home/home-view-model.ts(20,5): error TS2322: Type 'Promise<void>' is not assignable to type '{ source: Source; author: string; title: string; description: string; url: string; urlToImage: string; publishedAt: string; }[]'.
  Property 'length' is missing in type 'Promise<void>'.
app/home/home-page.ts(1,27): error TS2307: Cannot find module 'data/observable'.
app/home/home-page.ts(2,29): error TS2307: Cannot find module 'ui/layouts/stack-layout'.
app/home/home-view-model.ts(20,5): error TS2322: Type 'Promise<void>' is not assignable to type '{ source: Source; author: string; title: string; description: string; url: string; urlToImage: string; publishedAt: string; }[]'.
  Property 'length' is missing in type 'Promise<void>'.

Любая помощь приветствуется!

Ответы [ 2 ]

0 голосов
/ 14 декабря 2018

Я хотел быть уверенным и найти полное решение здесь.Мне нужно было назначить функцию getJSON переменной, чтобы заставить это работать.Обратите внимание на переменную fooBar ниже:

 allNews: { source: Source,
        author: string,
        title: string, 
        description: string, 
        url: string, 
        urlToImage: string, 
        publishedAt: string 
     }[]; // just declare the variable here

    getData = getJSON("newsapi link").then((r: any) => {
    this.allNews = r; // assign it from the response when successful
    }, (e) => {
    }); 
0 голосов
/ 05 декабря 2018

Вы присваиваете результат вызова .then, который является Обещанием.Оба вызова getJSON () и .then () возвращают обещания (чтобы разрешить цепочку).

Вместо этого вы хотите присвоить значение внутри обработчика разрешения обещания:

allNews: { source: Source,
           author: string,
           title: string, 
           description: string, 
           url: string, 
           urlToImage: string, 
           publishedAt: string 
        }[]; // just declare the variable here
 getJSON("newsapi link").then((r: any) => {
   allNews = r; // assign it from the response when successful
 }, (e) => {
 }); 

Вот ссылка с дополнительной информацией об обещаниях, которая может быть полезна: https://www.datchley.name/es6-promises/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...