我需要加入一个 Angular 项目,但对此几乎没有经验,有人可以帮助我如何向 app.routes.js 添加参数吗?
我有这个例子:
.state('product-article', {
resolve: {
productArticleData: getProductArticleData
},
url: '/product-article',
templateUrl: siteInfo.templateRoot + '/productArticlePage.html',
controller: 'ProductArticlePageController',
controllerAs: 'ProductArticlePageCtrl'
})
在同一个文件中我可以找到:
function getProductArticleData(ProductArticleApiService) {
return ProductArticleApiService.getData();
}
在 ProductArticleApiService.js 中我发现了这个:
angular.module('ourApp').factory('ProductArticleApiService', ['apiBase','$http', ProductArticleApiService]);
function ProductArticleApiService(apiBase, $http) {
return {
getData: function() {
return $http({
method: 'GET',
url: apiBase + '/product_article/98',
headers: {
'X-Siteaccess': 'eng'
}
});
}
};
};
现在我的任务是使其更加动态,以替换最后一个文件中的硬编码“98”和“eng”,因此我将这些参数添加到 getData() 函数中,并将它们也添加到 getProductArticleData 函数中:
function getProductArticleData(ProductArticleApiService, article_id, siteaccess) {
return ProductArticleApiService.getData(article_id, siteaccess);
}
但是当我尝试在 app.routes.js 中执行此操作时,事情出了问题:
resolve: {
productArticleData: getProductArticleData("98","eng")
},
(我知道,仍然不是动态的,但我认为这是要走的路) 这使我的应用程序崩溃。这是有道理的,因为我只给需要 3 个参数的函数提供 2 个参数。但是,在我进行所有这些更改之前,它起作用了。该应用程序怎么可能使用原始代码运行?在resolve:部分中,我没有将ProductArticleApiService作为参数提供给getProductArticleData函数,但它可以工作,但是当我添加额外的参数时,它就不行了?
最佳答案
上述问题(为什么它不能按预期工作)是 getProductArticleData
不实际上被视为正常函数。它的行为更像 Controller 中看到的函数,其中指定的参数实际上将由 Angular 注入(inject):
angular.module("ourApp").controller(function ($scope, Service1, Service2) {
// some code
});
因此,在您的示例中,ProductArticleApiService
是一个将被注入(inject)的 Angular 服务,您的应用程序可能已损坏,因为 Angular 现在正在尝试注入(inject) article_id
和 siteaccess
作为服务。因为(我假设)没有这样的服务,所以它失败了。
我怀疑您想要做的是允许在服务外部指定 $http
请求的参数。所以这可能就是您正在寻找的:
.state('product-article', {
resolve: {
// I moved the function here for clarity
// added $stateParams to be injected
productArticleData: function (ProductArticleApiService, $stateParams) {
return ProductArticleApiService.getData($stateParams.articleId, $stateParams.siteaccess);
}
},
// changed url
url: '/product-article/:articleId/:siteaccess',
templateUrl: siteInfo.templateRoot + '/productArticlePage.html',
controller: 'ProductArticlePageController',
controllerAs: 'ProductArticlePageCtrl'
})
这里需要注意一些事情:
- 我更改了网址以接受两个参数
:articleId
和siteaccess
,现在可以将其称为/product-article/98/en
> - 我更改了函数以接受
ProductArticleApiService
和$sateParams
。$stateParams
是一个“服务”,提供上面的 url 参数。
我强烈建议你深入了解 Angular 中的路由是如何工作的,特别是 ngRoute和 ui-router (它们相关但不同+您在代码中使用 ui-router)。
希望这足以帮助您入门。评论以澄清任何事情。
关于javascript - 在 Angular app.routes.js 解析函数中使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618360/