gpt4 book ai didi

angularjs - 在多 View 路由器中解析 $http GET 请求(使用 ui.router)

转载 作者:行者123 更新时间:2023-12-03 09:30:42 25 4
gpt4 key购买 nike

JS (app.js):

angular
.module("goHenry", ["ui.router"])
.controller("MainCTRL", MainCTRL)
.config(configB);



function MainCTRL($location){
this.nameApp = "goHenry";

}

JS (router.js):

function configB($urlRouterProvider, $stateProvider){        
$urlRouterProvider.otherwise("/");
$stateProvider
.state("/",{
url: "/",
templateUrl : "/testingBlock.htm",
controllerAs : "MainCTRL as ctrl"
})
.state("multi",{
url: "/multi",
views: {
"": {
templateUrl: "/multipleView.htm",
controllerAs: "MainCTRL as ctrl"
},
//blocks
"viewA@multi": {
resolve: {
getChildrenNumber: function($http){
//below here I'm simulating some GET answer
return "Some response from an API";
}
},
templateUrl: "/testingBlock.htm",
controllerAs: "MainCTRL as ctrl"
},
"viewB@multi": {
templateUrl: "/app/templates/login.htm",
controller: function($scope){
$scope.nameApp = "nameAppChanged";
//$scope.getChildrenNumber = getChildrenNumber;
}
}
}
});
}

我应该/可以在主视图或 subview 内解决请求吗?然后,我如何在 subview 和/或主/ View 中使用该结果,我的意思是在它们自己的 Controller 中。

最佳答案

a working plunker

让我们从 ViewA 和 ViewB 的 Controller 开始:

.controller('MainCTRL', ['$scope', 'getChildrenNumber', 
function($scope, getChildrenNumber) {
$scope.children = getChildrenNumber;console.log($scope.children)
}])
.controller('ViewBCtrl', ['$scope', 'getChildrenNumber',
function($scope, getChildrenNumber) {
$scope.children = getChildrenNumber;
}])

如果我们这样定义状态,它们将被正确地提供 'getChildrenNumber':

.state("multi", {
url: "/multi",
views: {
"": {
templateUrl: "multipleView.htm",
controllerAs: "MainCTRL as ctrl"
},
//blocks
"viewA@multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL",
controllerAs: "ctrl",
},
"viewB@multi": {
templateUrl: "app/templates/login.htm",
controller: "ViewBCtrl",
controllerAs: "ctrl",
}
},
resolve: {
getChildrenNumber: ['$http', function($http) {
return $http
.get("data.json")
.then(function(response){
console.log(response.data)
return response.data;
})
}]
},
});

正如我们所见 - 解析已从 1) View 级别定义移至 2) 状态级别定义。这意味着,我们可以在任何 View 的 Controller 中请求此类已解析的值

另外请注意,对于 UI-Router,我们应该使用这种 controllerAs 表示法:

"viewA@multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL", // controller name
controllerAs: "ctrl", // the AS part - what will be injected into $scope

查一下in action here

关于angularjs - 在多 View 路由器中解析 $http GET 请求(使用 ui.router),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30738236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com