所以我可以在 Jax-RS 中用我的资源类做这件漂亮的事情:
@Path("/clubs")
class ClubsResource {
@Path("/")
@GET
public Response getClubs() {
// return list of clubs
}
@Path("/{id}")
@GET
public Response getClub(@PathParam("id") long id) {
// return club with given id
}
//lots of other club endpoints
}
@Path("/people")
class PeopleResource {
@Path("/")
@GET
public Response getPeople() {
// return list of people
}
@Path("/{id}")
@GET
public Response getPerson(@PathParam("id") long id) {
// return person with id
}
//THIS IS THE NIFTY PART
@Path("/{id}/clubs")
public ClubsResource getClubStuffForPerson(@PathParam("id") long personId) {
return new ClubsResource(personId);
}
}
它的巧妙之处在于它允许我“扩展”PeopleResource
与 ClubsResource
- 它给了我端点 /people/1234/clubs
, /people/1234/clubs/5678
, 和 people/1234/clubs/<every other ClubsResource endpoint>
,几乎是免费的。
我想在我的 angular 应用程序中使用 ui-router 做一些类似的事情。
所以我有:
$stateProvider
.state('people', {
url: '/people'
}).state('people.detail', {
url: '/{personId}'
//lots of other people states
}).state('clubs', {
url: '/clubs'
}).state('clubs.detail', {
url: '/{clubId}'
}).state('clubs.detail.edit', {
url: '/edit'
})
// lots of other clubs states
我想“扩展”people.detail
状态与所有 clubs.*
状态(反之亦然):例如,我想要一个 people.detail.clubs
状态(在 url /people/1234/clubs
)向我展示了 1234 人的所有俱乐部。还有一个 clubs.detail.people
状态为 /clubs/5678/people
这显示了 5678 俱乐部的所有人。
显然我可以手动创建这些状态,但我想知道 ui-router 中是否存在类似于 Jax-RS 中子资源定位器的构造,允许我做我在那里做的事情(因为这会考虑到任意复杂的“俱乐部”和“人”状态,更易于维护)。
更新:作为实现此目标的一种骇人听闻且不完整的方式,我正在做:
//people_states.js
var list = {/* object-style definition of people list state */ };
var detail = {/* object-style definition of people detail state */ };
module.constant('PeopleStates', {
list: function(customUrl){
//param allows other states to use same definition with different URL
var toReturn = angular.copy(list);
toReturn.url = customUrl ? customUrl : toReturn.url;
return toReturn;
}
detail: function(url){/* same idea */ }
}
//club_states.js
//var list, detail... same idea
module.constant('ClubStates', {/*same idea*/})
module.config(function($stateProvider, PeopleStates, ClubStates){
$stateProvider
.state('clubs', ClubStates.list())
.state('clubs.detail', ClubStates.detail())
.state('clubs.detail.members', PeopleStates.list("/members"))
.state('clubs.detail.members.detail', PeopleStates.detail())
//^^ so URL is /clubs/5678/members/1234
})
这帮助我消除了大部分代码重复,但感觉很笨拙并且没有触及我的问题的核心——即 ui-router 是否提供了一种更优雅的方式来 native 执行此操作。
最佳答案
据我所知,ui-router
不支持开箱即用,所有 .state()
状态都必须声明为在 用户界面路由器
。支持的是状态是嵌套的,在进入子状态之前必须解决所有先前的状态。
我在多个状态下遇到了重复解析函数的类似问题,我通过将其抽象为与您所做的类似的服务来解决。
在其他项目中,我还做了一个函数,该函数基于一些参数生成完整的状态声明(名称、url、模板、ctrl、解析),因为我打开的状态更像是 20 个略有不同的模态:)
所以最后你抽象掉了状态定义的生成,这没问题。
关于javascript - Angular ui-router中的双向子/资源关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32194484/