gpt4 book ai didi

javascript - AngularJS Promise 的变量范围问题

转载 作者:行者123 更新时间:2023-12-03 08:21:54 24 4
gpt4 key购买 nike

我对 AngularJS 完全陌生,我尝试找出我的代码出了什么问题。

总的来说,这看起来是一个变量范围问题,但我不知道如何解决它:

这是我的代码:

'use strict';

(
function() {
/**
* @name angularApp.controller:LoginpageCtrl
* @description This controller is responsible to manipulate the user login process.
* @param themeConfigs Contains the site themeConfiguration options.
*/
var $userRegisterCtrl = function ( $window, $timeout, user, themeConfigs ) {
var $this = this;
$this.theme_configs = themeConfigs;
$this.username = '';
$this.email = '';
$this.password = '';
$this.error = '';
$this.success = '';

$this.register = function() {
user
.register(
$this.username,
$this.password,
$this.email
)
.then(
function( ) {
$this.success = 'Your account has been successfully created.<br />';
$this.success += 'Soon you will redirected in login page.';

$timeout(
function() {
$window.location.href = '/#/login';
},
4000
);
},
function( $error_message ) {
console.log( $error_message );
}
);
};
};

$userRegisterCtrl.$inject = [ '$window', '$timeout', 'user', 'themeConfigs' ];

angular.module('angularApp' ).controller( 'userRegisterCtrl', $userRegisterCtrl );
}
)();

我得到的错误如下:

TypeError: Cannot set property 'success' of undefined
at register.js:27
at processQueue (angular.js:14745)
at angular.js:14761
at Scope.parent.$get.Scope.$eval (angular.js:15989)
at Scope.parent.$get.Scope.$digest (angular.js:15800)
at Scope.parent.$get.Scope.$apply (angular.js:16097)
at done (angular.js:10546)
at completeRequest (angular.js:10744)
at XMLHttpRequest.requestLoaded (angular.js:10685)

因此第 27 行与以下两行相关:

$this.success = 'Your account has been successfully created.<br />';
$this.success += 'Soon you will redirected in login page.';

但是为什么 $this.success 超出了范围?我该如何解决这个问题?有没有与 promise 相关的技巧?

最佳答案

你能尝试将 $this 重命名为 _this 吗?通常 Angular 使用 $ 作为其服务和变量,

  • $索引
  • $id
  • $这个

所有示例

您的问题与作用域变量无关,而是与 $this 未定义有关。

关于javascript - AngularJS Promise 的变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707739/

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