AngularJS:如何通过$ http获取数据时禁用默认观察者

我使用$ 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();

};

}]

};

}])

当获取请求接收到数据时,默认观察者以及启动和无限循环再次调用该数据。如何禁用它们或以任何其他方式解决此问题。

回答:

通过scope方法进行API调用不是一个理想的解决方案,因为它们将由于$digest周期而被多次评估。您可以为此使用callbackspromises,并可以删除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;

});

}]

};

}])

OR

无极

.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;

});

}]

};

}])

请注意无极链的使用在上述溶液

以上是 AngularJS:如何通过$ http获取数据时禁用默认观察者 的全部内容, 来源链接: utcz.com/qa/263489.html

回到顶部