我使用$ http.get获取身份验证和用户详细信息,以便我可以显示用户名而不是登录按钮。
.directive("plunkerUserPane", ["collectionsManager", function(collectionsManager) {
var getAuth = function($http) {
$http.get('/user/auth').success(function(response) {
if (response.isAuth) {
return 'user.html';
} else {
return 'userPane.html';
}
});
};
return {
restrict: "E",
replace: true,
template: '<div ng-include src="userPane.getTemplate()"></div>',
controllerAs: "userPane",
controller: ["$scope", "$http", "login", "visitor", function($scope, $http, login, visitor) {
this.visitor = visitor;
this.getTemplate = function() {
var template = 'userPane.html';
template = getAuth($http);
return '/components/userPane/' + template;
}
this.showLoginWindow = function() {
login.open();
};
}]
};
}])
当get请求收到数据时,默认观察者和启动和无限循环再次调用它。如何禁用它们或任何其他方法来解决此问题。
答案 0 :(得分:0)
对scope
方法进行API调用不是理想的解决方案,因为它们会因$digest
周期而被多次评估。您可以使用callbacks
或promises
进行此操作,并可以从模板中删除method
以发出http
请求。
见下文
<强>回调强>
.directive("plunkerUserPane", ["collectionsManager", function(collectionsManager) {
var getAuth = function($http, cb) {
$http.get('/user/auth').success(function(response) {
if (response.isAuth) {
cb('user.html');
} else {
cb('userPane.html');
}
});
};
return {
restrict: "E",
replace: true,
template: '<div ng-include src="userPane.template"></div>',
controllerAs: "userPane",
controller: ["$scope", "$http", "login", "visitor", function($scope, $http, login, visitor) {
var self = this;
self.visitor = visitor;
self.template = 'userPane.html';
self.showLoginWindow = function() {
login.open();
};
getAuth($http, function(template) {
self.template = '/components/userPane/' + template;
});
}]
};
}])
或强>
<强>无极强>
.directive("plunkerUserPane", ["collectionsManager", function(collectionsManager) {
var getAuth = function($http, cb) {
return $http.get('/user/auth').then(function(response) {
if (response.isAuth) {
return 'user.html';
} else {
return 'userPane.html';
}
});
};
return {
restrict: "E",
replace: true,
template: '<div ng-include src="userPane.template"></div>',
controllerAs: "userPane",
controller: ["$scope", "$http", "login", "visitor", function($scope, $http, login, visitor) {
var self = this;
self.visitor = visitor;
self.template = 'userPane.html';
self.showLoginWindow = function() {
login.open();
};
getAuth($http).then(function(template) {
self.template = '/components/userPane/' + template;
});
}]
};
}])
请注意上述解决方案中Promise Chain的使用