【问题标题】:How to load local json file in ionic cordova on android device如何在 android 设备上的 ionic cordova 中加载本地 json 文件
【发布时间】:2016-06-23 00:12:36
【问题描述】:

这是我的角度控制器:

.controller( 'QuestionsController', function( $scope, $state, $http, $ionicSlideBoxDelegate, $q ) {
var answer = null;  // global answer variable
var totalScore = 0; // global totalScore variable

$scope.init = function() {
    // the question number
    $scope.questionNumber = 1;

    $scope.getQuestions().then( function( res ) {
        alert( res );
        $scope.questionList = res;
    }, function( err ) {
        alert( err );
        console.log( status );
    })
};

// this fetches the questions from the json data source.
$scope.getQuestions = function() {
    var defer = $q.defer();

    $http.get( 'data/data.json' ).success( function( data ) {
        defer.resolve( data );
    }, function( status ) {
        defer.reject( status );
    });

    return defer.promise;
};

我已尝试将 json 文件路径替换为以下内容,但仍然无法正常工作:

$http.get('file:///android_asset/www/data/data.json')

$http.get('./data/data.json')

我真的需要帮助,并且在 android 版本 5.1 (Lollipop) 上运行

【问题讨论】:

  • 你的文件结构是什么?

标签: android angularjs json cordova ionic-framework


【解决方案1】:

角度 $http.get 是返回一个 httpPromise

它有三个方法,thencatchfinally

没有successerror

参见https://docs.angularjs.org/api/ng/service/$q(Promise API)

所以,你只需要修改你的代码

$http.get( 'data/data.json' ).then( function( data ) {
    defer.resolve( data );
}, function( status ) {
    defer.reject( status );
});   

【讨论】:

  • 在我的浏览器中运行良好,但在 Android 设备上却不行
【解决方案2】:

你可以这样使用

 $http.get('data/data.json')
        .then(function(response){
           $scope.data1=response.data;

        },function(error){
          $log.error(error);
      });

【讨论】:

  • 在我的浏览器中工作得很好,但在 Android 设备上却不行
【解决方案3】:

只是需要检查一下 - android 文件请求区分大小写。 $http.get 中大小写错误的文件名可以在浏览器上工作,但不能在设备上工作,因此对 Friends.json 的调用与 Friends.json 不同

【讨论】:

    【解决方案4】:
    $http.get('js/contactos.json').then(
                    function(response){
                        console.info(response.data);
                    },function(error){
                        console.error(error);
                    });
    

    我的json文件路径是:www/js/contactos.json

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 2019-12-16
      • 2016-12-24
      • 2018-02-26
      • 1970-01-01
      • 2017-05-08
      • 2012-06-01
      • 2019-03-03
      • 2011-04-23
      相关资源
      最近更新 更多