【问题标题】:Conflict between Angular JS $scope and the MIME content-type of an API http response?Angular JS $scope 和 API http 响应的 MIME 内容类型之间的冲突?
【发布时间】:2015-03-04 01:14:37
【问题描述】:

我正在使用 AngularJs 应用程序,通过 $http 使用 Slim PHP 使用 API REST(下一步:$resource,我知道)。当控制器这样编写时,从 API 检索数据时一切正常:

angular
    .module("adminTaller", ['ngRoute'])
           ...
    .controller("CustomersListController", ['$http', function($http){
        var ctrl = this;
        ctrl.customers = [];
        $http.get('api/customers')
            .success(function(data, status, headers, config){
                ctrl.customers = data;
            })
            .error(function (data, status, headers, config) {
                ...
            });
    }]);

“客户”显示在此视图中:

<div ng-controller="CustomersListController as lstCtrl">
<input type="text" ng-model="searcher" />
<table>
    <thead>
    <tr>
        <th>Apellido y Nombres</th>
        <th>Domicilio</th>
        <th>TE Celular</th>
        <th>TE Comercial</th>
        <th>TE Domicilio</th>
        <th>Acciones</th>
    </tr>
    </thead>
    <tbody ng-repeat="customer in lstCtrl.customers | filter:searcher | orderBy: fullname">
    <tr>
        <td>{{ customer.fullname }}</td>
        <td>{{ customer.address }}</td>
        <td>{{ customer.cellphone }}</td>
        <td>{{ customer.businessphone }}</td>
        <td>{{ customer.homephone }}</td>
        <td><a href="#">Editar</a></td>
    </tr>
    </tbody>
</table>

但在我将 this 替换为 $scope 的那一刻:

angular
  .module("adminTaller", ['ngRoute'])
                ...
  .controller("CustomersListController", ['$http', '$scope', function($http, $scope){
            var ctrl = $scope;
            ctrl.customers = [];
            $http.get('api/customers')
                .success(function(data, status, headers, config){
                    ctrl.customers = data;
                })
                .error(function (data, status, headers, config) {
                    ...
                });
        }])

,似乎什么都没有发生(我的意思是,表中没有加载“客户列表”),并且 Batarang 给了我一个奇怪的警告(如果 Batarang 被禁用,Chrome 的控制台什么也没说):

资源解释为脚本但以 MIME 类型传输 应用程序/x-js

我的 api/index.php 将 content-type 设置为 application/json

$app = new Slim();

$app->response()->header('Content-Type', 'application/json');

$app->get('/customers', 'getCustomers');
$app->post('/customers', 'addCustomer');
$app->get('/customers/:id', 'getCustomer');
$app->put('/customers/:id', 'updateCustomer');
$app->delete('/customers/:id', 'deleteCustomer');

$app->run();

事实上,http 请求和 http 响应标头对我来说看起来不错:

Remote Address:[::1]:8080
Request URL:http://localhost:8080/ng-taller/api/customers
Request Method:GET
Status Code:200 OK
**Request Headers**
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6,pt;q=0.4
Connection:keep-alive
Cookie:__ngDebug=true; PHPSESSID=b8cedd49edcc461fda62208e66cfb150; b8cedd49edcc461fda62208e66cfb150=DEFAULT%7C0%7C2M3TMlgUx3gTlaarYzHIdD28l8q9FTcNubt55%2BUGpAo%3D%7C7456bf61db3500c8bb7b3bc38082a470ce4a2ad3
Host:localhost:8080
Referer:http://localhost:8080/ng-taller/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
**Response Headers**
Connection:Keep-Alive
Content-Length:1027
Content-Type:application/json
Date:Wed, 04 Mar 2015 00:26:12 GMT
Keep-Alive:timeout=5, max=97
Server:Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.19
Set-Cookie:b8cedd49edcc461fda62208e66cfb150=DEFAULT%7C0%7C2M3TMlgUx3gTlaarYzHIdD28l8q9FTcNubt55%2BUGpAo%3D%7C7456bf61db3500c8bb7b3bc38082a470ce4a2ad3; path=/
X-Powered-By:PHP/5.4.19

当我使用 Batarang 检查视图的范围/模型时,它显示:

    { 
lstCtrl:  {  } 
customers: 
[  { 
id: 2
createdAt: 03-03-2015
fullname: Abelardini, Antonio Miguel
address: Virasoro Nº2533, Piso 3º - Rosario
cellphone: 341 (15)562-4484
businessphone: 341 430-4574
homephone: 
observations: 
logs: 
[  ]
errors: 0
 } ,  { 
id: 1
createdAt: 03-03-2015
fullname: Alvarez, Juan
address: Gallo Nº1254 (entre Nuria y Valdez) - Rosario
cellphone: 341 (15)485-6225
businessphone: 
homephone: 
observations: Puntual en el pago
logs: 
[  ]
errors: 0
 } ,  { 
id: 4
createdAt: 03-03-2015
fullname: Blanco de Escalada, María de las Mercedes
address: Av. Álvarez Thomas Nº1542, Piso 11º Depto.'A' - Rosario
cellphone: 341 (15)326-5484
businessphone: 
homephone: 
observations: 
logs: 
[  ]
errors: 0
 } ,  { 
id: 3
createdAt: 03-03-2015
fullname: Tirado López, Juan Manuel
address: Costanera Nº12 (Bajada de los Pescadores) - Rosario
cellphone: 341 (15)675-1125
businessphone: 
homephone: 3205 124-8586
observations: 
logs: 
[  ]
errors: 0
 }  ]
 } 

【问题讨论】:

  • 如果要使用$scope,只需使用$scope(无需分配给ctrl)。您还需要删除 as lstCtrl 并直接在 HTML 中引用 customers。您可能应该阅读一下何时使用 controller as 表单以及与控制器范围有什么区别
  • 谢谢@Phil,我会考虑的!你有什么建议我可以阅读更多关于它的信息吗?我当然对此感到困惑,Angular's controller documentation 没有解释它.. 我得到的消息来源也没有!提前致谢!

标签: json angularjs angularjs-scope mime-types


【解决方案1】:

我认为这与 mime 类型没有任何关系。

在您看来,您是否也将“lstCtrl.customers”更改为“customers”?否则,您将指向一个没有任何内容的控制器。

顺便说一句,你第一次使用的方法是更好的方法。首选使用 controllerAs 语法。

【讨论】:

  • “首选使用 controllerAs 语法” ~ 有参考吗?
  • 不,我不知道。我只是在我的日常工作中每天都使用 angularJS,并跟随新的 angular 发展。 ControllerAs 相对较新。添加它是为了弥补旧的做事方式(将所有内容都放在范围内)的一些缺陷。我可以给出的最简单的原因是 ControllerAs 可以明确您的目标控制器(或范围)。如果您的元素具有与“fooCtrl.bar”的 ng-model 绑定,则您不太可能在错误的范围内引用“bar”。当您在大型团队中工作时,很可能会发生数据冲突。
  • "否则,您将指向一个没有任何内容的控制器。"这是未显示数据问题的关键,我猜...... mime-warning 仍然存在,但它与问题无关(我现在可以忍受它)!
猜你喜欢
  • 2017-10-07
  • 2012-11-12
  • 1970-01-01
  • 2019-01-01
  • 2021-03-07
  • 2017-04-25
  • 1970-01-01
  • 2011-08-27
  • 2019-07-08
相关资源
最近更新 更多