我有一个Angular Ionic应用程序。我在其路线中分配了控制器,模板及其解决方案。这工作正常,以便我的主控制器仅在父控制器的所有承诺解决后加载。 但是如果这个路由包含另一个带有一些承诺的子控制器。这里的问题是页面只需要在父和子控制器的所有承诺解决后加载。
var app = angular.module('testApp', ['ionic']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('dashboard', {
url: "/dashboard",
templateUrl: "dashboard.html",
controller: 'DashboardController',
title: 'Dashboard',
resolve: {
UserDetails: function(DataService) {
return DataService.getUserDetails(1);
},
DashboardDetails: function(DataService) {
return DataService.getDashboardDetails();
}
}
});
$urlRouterProvider.otherwise('/dashboard');
});
app.factory('DataService', function($q) {
return {
getUserDetails: function(id){
var defer = $q.defer();
var userDetails = {
name: "Saidh"
}
defer.resolve(userDetails);
return defer.promise;
},
getDashboardDetails: function(){
var defer = $q.defer();
var dashboardDetails = {
title: "Dashboard"
}
defer.resolve(dashboardDetails);
return defer.promise;
}
}
});
app.controller('HeaderController', function($scope, UserDetails) {
console.log(UserDetails);//Error: [$injector:unpr] Unknown provider:
$scope.userDetails = UserDetails;
});
app.controller('DashboardController', function($scope, DashboardDetails) {
console.log(DashboardDetails);//Working: show result
$scope.dashboardDetails = DashboardDetails;
});
我怎样才能做到这一点?
答案 0 :(得分:1)
简单添加嵌套状态,每个州都应拥有自己的resolve: somePromise
属性here i fork your plunkr并添加超时,以便父视图和子视图仅为promise
为solved
示例:
$stateProvider.state('header', {
url: "/home",
templateUrl: "header.html",
controller: 'HeaderController',
resolve: {
UserDetails: function(DataService) {
return DataService.getUserDetails(1);
}
}
});
$stateProvider.state('header.dashboard', {
url: "/dashboard",
controller: 'DashboardController',
templateUrl: "dashboard.html",
parent: 'header',
resolve: {
DashboardDetails: function(DataService) {
return DataService.getDashboardDetails();
}
}
});
这是非常具有战略意识的前锋
答案 1 :(得分:0)
你只能在DashboardController
内得到解决方案的承诺,你永远不会在html模板内的家庭控制器内得到它。
路由器state
本身提到的控制器内部提供了解析服务。因此,您可以访问DashboardController
中的依赖项,将其置于范围变量&使它可用于子范围并查看。
此外,您需要从UserDetails
移除HomeController
依赖项以消除错误,因为UserDetails
永远无法访问
<强>代码强>
app.controller('DashboardController', function($scope, DashboardDetails, UserDetails) {
console.log(UserDetails); //Working: show result
$scope.dashboardDetails = DashboardDetails;
$scope.userDetails = UserDetails;
});
请参阅Working Plunkr此处