gpt4 book ai didi

javascript - 服务调用后 Angular 方法未在 Controller 中触发

转载 作者:行者123 更新时间:2023-11-29 21:35:22 25 4
gpt4 key购买 nike

我有一个 Angular 服务,它获取作为 promise 解析的 currentuser 对象。我有一个部分由一个对象 userdetails 填充,该对象在方法调用内部调用,但不幸的是,在解决 promise 后调用时,方法调用未触发。

.controller('AccountCtrl', [
'$scope', 'userService', '$compile', '$http', 'utility', 'cloudService', function ($scope, userService, $compile, $http, utility, cloudService) {

$scope.userdetails = {};
$scope.downloadPageChk = $scope.paymentHistoryPageChk = $scope.manageGroupsPageChk = "hide";
$scope.getUserAttribute = function (param, x) {
return userService.getAttribute(param, x);
};
cloudService.fetchCurrentUser().then(function (newCurrentuser)
{
if (newCurrentuser)
{
$scope.currentUser = newCurrentuser;
$scope.getUserDetails = function()
{
if (userService && userService.isLoggedIn())
{
$scope.userdetails = JSON.parse(JSON.stringify(currentUser));
}
};

if (newCurrentuser == 'member') {
if (newCurrentuser.features.download) $scope.downloadPageChk = "show";
if (newCurrentuser.features.paymenthistory) $scope.paymentHistoryPageChk = "show";
if (newCurrentuser.group.enabled) $scope.manageGroupsPageChk = "show";
}
}
}
])

partial
<div data-ng-controller="AccountCtrl">
<div data-ng-init="getUserDetails()">
<input type="text" class="form-control pull-left" id="FirstName" name="FirstName" data-placeholder-attr="First Name" data-ng-model="userdetails.firstname" required>
<input type="text" class="form-control pull-left" id="LastName" name="LastName" data-placeholder-attr="Last Name" data-ng-model="userdetails.lastname" required>
</div>
</div>

请让我知道我错过了什么。我现在苦苦思索了 10 个小时,如果我将用户详细信息移出,如果 cloudservice.fetchuser().then() 它至少会调用该函数,但不确定将其放入其中时会发生什么。

Similar plunk created here http://plnkr.co/edit/pLAB4VpLU7uhlSibHzXP?p=preview谢谢

最佳答案

如果您只想初始化数据 - 您不需要 $scope.getUserDetails 函数和 data-ng-init="getUserDetails()".

Angular 将执行服务 fetchCurrentUser 函数并在加载时填充 $scope.userdetails

cloudService.fetchCurrentUser().then(function (newCurrentuser)
{
if (newCurrentuser)
{
$scope.currentUser = newCurrentuser;
if (userService && userService.isLoggedIn())
{
$scope.userdetails = JSON.parse(JSON.stringify($scope.currentUser));
}

if (newCurrentuser == 'member') {
if (newCurrentuser.features.download) $scope.downloadPageChk = "show";
if (newCurrentuser.features.paymenthistory) $scope.paymentHistoryPageChk = "show";
if (newCurrentuser.group.enabled) $scope.manageGroupsPageChk = "show";
}
}
}
}

参见 plunker .

编辑:

如果您希望 getUserDetails 函数在初始化后仍可触发,您应该将其放在服务方法之外:

$scope.getUserDetails = function(){
if (userService && userService.isLoggedIn()){
$scope.userdetails = JSON.parse(JSON.stringify($scope.currentUser));
}
};

然后根据需要触发它(通过 View 中的 ng-click="getUserDetails()" 或 Controller 中的 $scope.getUserDetails())。

关于javascript - 服务调用后 Angular 方法未在 Controller 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001159/

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