我在获取状态参数的控制器时遇到了一些麻烦。我正在使用正确的状态链接到下一个视图。
<td><a ui-sref="orders({customerId: cust.id})">View Orders</a></td>
在我的配置文件中,我引用了该名称和路由参数的状态。我现在注释掉了解析对象。我的目标是进入控制器,然后传递正确的数据。 请注意,我正在使用 controllerAs
我最初的想法是({customerId: ctrl.cust.id }) 但是这并没有改变 url 路由。url 正在更改以匹配 url 名称,但没有连接到控制器,也没有给我视图。
(function() {
'use strict';
angular
.module('app.orders')
.config(config);
function config($stateProvider) {
$stateProvider
.state('orders',{
// params: {customerid: null},
url:'/customers:customerId',
templateUrl: './components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl',
resolve: {
customerFactory: 'customerFactory',
customerInfo: function( customerFactory, $stateParams) {
return customerFactory.getCustomers($stateParams.id);
}
}
************** 我的主要问题是解决方法。这阻止我进入下一个控制器。*****************
resolve: {
customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
return customerFactory.getCustomers($stateParams.id);
}]
}
})
};
})();
现在我的控制器非常小。我只想连接到它。我检查了我的网络选项卡并查看GET文件。
(function() {
// 'use strict';
angular
.module('app.orders')
.controller('OrdersController', OrdersController);
function OrdersController($stateParams) {
console.log('in');
var vm = this;
vm.title = "Customer Orders";
vm.customer = null;
}
}());
我在主 javascript 文件中引用了我的模块。
(function () {
'use strict';
angular.module('app', ['app.services',
'app.customers',
'app.orders','ui.router']);
})();
当我注释掉解析时,我可以访问控制器。所以我知道问题正在解决中。这是我的服务。我正在使用 $http 请求并使用.then向 Json 文件发出请求
更新这是我重构的服务调用,我每次都在控制台中找回正确的客户。
(function() {
angular
.module('app.services',[])
.constant('_', window._)
.factory('customersFactory', customersFactory);
function customersFactory($http, $log) {
return {
getCustomers: getCustomers,
getCustomer: getCustomer
};
function getCustomers(){
return $http.get('./Services/customers.json',{catch: true})
.then(getCustomerListComplete)
.catch(getCustomerListFailed);
function getCustomerListComplete(response) {
console.log('response.data',response.data);
return response.data;
}
function getCustomerListFailed(error) {
console.log('error', error);
}
}
function getCustomer(id) {
var url = './Services/customers.json';
return $http.get(url, {
catch: true
})
.then(function(response) {
console.log('promise id',id);
var data = response.data;
for(var i =0, len=data.length;i<len;i++) {
console.log('data[i].id',data[i].id);
if(data[i].id === parseInt(id)) {
console.log('data[i]', data[i]);
return data[i];
}
}
})
}
}
}());