ui-router
中的子状态组件在阅读其父母数据时遇到问题。记录$stateParams
时,它会显示正确的信息。此数据作为参数传递给ui-sref
属性,这将导致向用户显示正确的信息,但它不是。
以下是要记录的项目ID(取决于点击的项目)。
为什么子状态patents.patent
无法从父状态patents
读取数据?
var app = angular.module('myApp', ['ui.router']);
app.config(['$stateProvider', function($stateProvider) {
var states = [
{
name: 'patents',
url: '/patents',
component: 'patents',
resolve: {
patents: function(patentsService) {
return patentsService.fetchAllPatents();
}
}
},
{
name: 'patents.patent',
url: '/{patentId}',
component: 'patent',
resolve: {
patent: function(patents, $stateParams) {
return patents.find(function(patent){
return patent.id === $stateParams.patentId;
})
}
}
}
]
states.forEach(function(state) {
$stateProvider.state(state);
});
}]);
app.service('patentsService', function($http) {
var service = {
fetchAllPatents: function() {
return $http.get('http://localhost:8080/Sprint002b/restpatent/', {cache: true}).then(function(resp){
return resp.data
});
}
};
return service;
});
部件
angular.module('myApp').component('patents', {
bindings: { patents: '<' },
template: ' <div>' +
'<div>' +
'<table>' +
'<thead>' +
'<tr>' +
'<td>Application No. </td>' +
'<td>Client Ref</td>' +
'<td>Cost now</td>' +
'<td>Cost band end</td>' +
'<td>Cost next</td>' +
'<td>Renewal Date</td>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr ng-repeat="patent in $ctrl.patents">' +
'<td><a ui-sref="patents.patent({patentId: patent.id})" ng-bind="patent.applicationNumber"></a></td>' +
'<td ng-bind="patent.clientRef"></td>' +
'<td ng-bind="patent.currentRenewalCost">$</td>' +
'<td ng-bind="patent.costBandEndDate"></td>' +
'<td ng-bind="patent.renewalCostNextStage"></td>' +
'<td ng-bind="patent.renewalDueDate"></td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'<div ui-view></div>' +
'</div>' +
'</div>'
});
angular.module('myApp').component('patent', {
bindings: { patent: '<' },
template: '<h3>A patent!</h3>' +
'<div><p>Name: {{$ctrl.patent.id}}</p></div>' +
'<div><p>Id: {{$ctrl.patent.applicationNumber}}</p></div>' +
'<div><p>Company: {{$ctrl.patent.clientRef}}</p></div>' +
'<button ui-sref="people">Close</button>'
});
更新
我设法用数据填充子状态,但只填充JSON对象中的第一个项目。
我更改了配置文件中resolve
属性中返回的数据。正在加载数据,但在选择项目时不会更改。
关于我应该做什么的任何想法?这一切都在plunkr https://plnkr.co/edit/jbZgIg?p=preview
中进行{
name: 'patents.patent',
url: '/{patentId}',
component: 'patent',
resolve: {
patent: function(patents, $stateParams) {
return patents.find(function(patent){
return $stateParams; // changed from patent.id === $stateParams.patentId
})
}
}
}
答案 0 :(得分:0)
使用严格的相等运算符而不是等于。所以代码现在是:
{
name: 'patents.patent',
url: '/{patentId}',
component: 'patent',
resolve: {
patent: function(patents, $stateParams) {
return patents.find(function(patent){
return patent.id == $stateParams.patentId; //not === operator
})
}
}
}