【问题标题】:Angularjs: Why data fetched by service query is treated like object and won't be used by AngularAngularjs:为什么服务查询获取的数据被视为对象并且不会被Angular使用
【发布时间】:2014-05-19 17:43:19
【问题描述】:

在我的服务(工厂)中,我执行查询以从我的服务器 PHP 页面获取数据。 两种情况:

  1. 如果我通过调用函数(返回数组)提供数组,然后回显 json_encode($data);在底部,Angular 会抱怨资源配置错误(比如数据类型错误,对象而不是数组,反之亦然,我会根据我是否设置 isArray true 或 false 来说);

  2. 如果我创建一个相同结构的数组并注释掉其他代码,只留下 echo json_encode($data);在底部,该死的东西会使用这些数据!

最让我惊讶的是 - 如果我打开 2 个选项卡,并且 print_r 或 var_dump 两种数组类型,它们将完全相同!

// I call my function to retrieve Google Plus posts like this
// in my response.php file which is being called for data
$pluses = $serviceObj->loadActivities($uId);

// That method creates then returns the resulting array
// note that I have to reach deeper into the response to take out just the 
// level i'm interested in - that is "items". 
// I used $key here to make sure each post is numerically indexed
// and I don't think that is the culprit but who knows..

public function loadActivities($uId)
{
    $items = array();
    $response = $this->service->activities->listActivities($uId, 'public', array('maxResults'=>4));
    foreach($response['modelData']['items'] as $key => $item){
        $items[$key]['displayName'] = $item['actor']['displayName'];
        $d = new \DateTime($item['published']);
        $items[$key]['publishedDate'] = $d->format("n/j/Y");
        $items[$key]['publishedMonth'] = $d->format("F");
        $items[$key]['imageSrc'] = $item['object']['attachments'][0]['image']['url'];
        $items[$key]['content'] = $item['object']['content'];
    }

    return $items;
}

// Now, this array looks like this when I do print_r on it
$arr = array(
    0 => array(
        'displayName' => 'thevalue',
        'publishedDate' => 'thevalue',
        'publishedMonth' => 'thevalue',
        'imageSrc' => 'thevalue',
        'content' => 'thevalue'
    ),
    1 => array(
        'displayName' => 'thevalue',
        'publishedDate' => 'thevalue',
        'publishedMonth' => 'thevalue',
        'imageSrc' => 'thevalue',
        'content' => 'thevalue'
    ),
    ....
);

// at the bottom of the file, there is this
echo json_encode($arr);
// so that Angularjs can get the data. This does not work (the error 
// at the bottom of this question is triggered

我什至尝试将手动输入的数组从 PHP 页面移动到我的函数中,该函数返回上面案例 1 中的数组 - 然后返回该数组(我这样做是为了测试相同的数组) - 仍然错误!

// so basically, if I manually type the same array but directly in 
// the response.php file, that is, the array is no longer returned by the function,
// and then
echo json_encode($arr);
// at the bottom, Angularjs stops complaining and consumes it.

我的服务

angular.module('socialPosts.services', ['ngResource'])
    .factory('PostsResource', ['$resource', function($resource){
            return $resource('response.php', {}, {
                query: { method: 'GET', isArray: true }
            })
    }])
;

我的控制器

angular.module('socialPosts.controllers', [])
    .controller('LoadPostsCtrl', ['$scope', 'PostsResource', function($scope, PostsResource){
            $scope.init = function(network, ename){
                $scope.entry = ename;
                $scope.loadTabContent(network);
            };
            $scope.content = [];
            $scope.loadTabContent = function(called){
                $scope.networkCalled = called;
                $scope.content = PostsResource.query( {from: $scope.networkCalled, company: $scope.entry } ).$promise.then(
                        function(result){
                                $scope.content = result;
                        },
                        function(error){
                            alert(error);
                        }
                    );
            };
    }]);

我别无选择,只能假设这与数据是通过函数调用获得的事实有关,因为无论如何我都是从我的服务器(PHP 页面)获取数据。

实际错误:

错误:$resource:badcfg 响应与配置的参数不匹配 资源配置错误。包含数组但得到对象的预期响应 描述 当 $resource 服务期望可以反序列化为数组、接收对象或反之亦然的响应时,会发生此错误。默认情况下,所有资源操作都需要对象,除了需要数组的查询。

要解决此错误,请确保您的 $resource 配置与服务器返回的数据的实际格式相匹配。

有关详细信息,请参阅 $resource API 参考文档。

【问题讨论】:

  • 这是 PHP 的一个常见错误,与 PHP 可能会根据类型和其键的值。您的$resource 请求需要 JSON 编码的数组或 JSON 编码的对象,但 PHP 不会以该格式返回它(即,它选择将“事物”编码为关联数组而不是索引数组(这会导致 JSON 编码对象而不是 JSON 编码数组),反之亦然)。显示一些代码可能会导致确切的问题和解决方案。
  • @ExpertSystem 好的,我刚刚添加了一些代码块,可能会对正在发生的事情有所了解。

标签: javascript php arrays angularjs angularjs-directive


【解决方案1】:

看起来很奇怪,但事实证明,应该有帮助的东西实际上是罪魁祸首。注释掉一行后

error_reporting(E_ALL);

函数返回的结果数组起作用了!

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多