【问题标题】:unable to read a data from a external JSON file : Ionic无法从外部 JSON 文件读取数据:Ionic
【发布时间】:2018-11-13 17:28:36
【问题描述】:

我已经在一个名为ionic-config.JSON 的 JSON 文件中配置了所有 URL。数据是这样的

[
    {
        "db_url": "http://localhost:3000/users/"
    }
]

我正在尝试使用GET 方法读取数据。

url: string = '../ionic-config/ionic-config.json';
this.http.get(this.url).subscribe( (data: any) => {
      this.db_url = data;
    })

但我收到一个错误,因为 404 找不到

GET http://localhost:8100/ionic-config/ionic-config.json 404 (不是 找到)

文件在目录src/ionic-config/ionic-config.json

【问题讨论】:

    标签: angular ionic-framework ionic2 ionic3


    【解决方案1】:

    您的路径似乎有问题。

    试试这个:

    url: string = 'ionic-config/ionic-config.json';
    

    另外,您分配 db_url 值的逻辑是错误的。您正在分配整个数组,而不是数组中特定对象的字段。改用这个:

    this.db_url = data[0].db_url;
    

    【讨论】:

    • 我试过了,错误没有变化。我从服务文件中调用它。目录为src/services/AU.ts
    【解决方案2】:

    您不需要向同一台服务器发出 http 请求。在您的应用程序中使用 JSON 文件:

    例如,如果您的 JSON 文件位于 /src/pages/YourPage/myJson.json 中,则转到您的 YourPage.ts(与您的 JSON 位于同一文件夹中)并说 import * as jsonData from './myJson.json';

    现在您可以将其用作普通 JSON 对象而无需对其进行解析。

    例如:(因为你的 JSON 是一个对象数组):

    console.log(jsonData[0].db_url);
    

    【讨论】:

    • 我已经尝试使用关键字 import 作为 import * as dbUrl from '../assets/ionic-config.json'; 但我得到的错误是 Cannot find module '../assets/ionic-config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension 。我已将 json 文件粘贴到 assets 文件夹中。
    • 我看到了你的错误。试试import * as dbUrl from '../../assets/ionic-config.json'
    • 您的链接指向了错误的文件夹,但现在应该可以使用
    • 不,我正确使用定向到文件夹。我使用 vscode 它显示下拉菜单,因此我已正确导航。我试过你的代码也显示同样的错误。
    【解决方案3】:

    您可以选择以下任何一种方式。

    1。使用 API 调用

    一个。只需将 ionic-config.json 文件移动到 assets 文件夹以获得更好的代码流。然后像这样进行 api 调用。

    return this.http.get('assets/ionic-config.json')
        .map(res=> return res.json);
    

    b.在您的.ts file 中订阅这样的 api 调用

    <method_name_in_service_file>.subscribe(resp=>{
     this.db_url = resp;
    },error=>{
       console.log(error)
    })
    

    2。直接从 ionic-config 文件导入

    喜欢这个

    import * as dbUrl from '<path to the config file>'
    

    你会得到来自dbUrl[0].db_url的url

    【讨论】:

    • 我已经尝试使用关键字 import 作为 import * as dbUrl from '../assets/ionic-config.json'; 但我得到的错误是 Cannot find module '../assets/ionic-config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension 。我已将 json 文件粘贴到 assets 文件夹中。
    • 只使用 assets/
    猜你喜欢
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2018-12-20
    相关资源
    最近更新 更多