$http服务未触发成功或错误回调

$http service not triggering success or error callbacks

本文关键字:成功 错误 回调 http 服务      更新时间:2023-09-26

这是我的部分视图-

<form action="" ng-controller="Ctrl as forgot" name="forgotForm" ng-submit="forgotForm.$valid && forgot.sendPost()">
        <div class="form-group row">
            <label for="email" class="col-sm-2 form-control-label">Email address</label>
            <div class="col-sm-9">
                <input type="email" ng-model="forgot.emailData" class="form-control" id="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+'.[a-z]{2,3}$" placeholder="Email Address" required/>
            </div>
        </div>
        <div class="form-group row">
            <div>
                <button class="btn btn-info submitButton">Submit</button>
            </div>
        </div>
    </form>

这是我的控制器中的一种方法-

self.sendPost = function() {
        console.log(self.emailData); //the value I entered in the input box
        $http.get("https://api?email=rq895@msstae.edu")
            .success(function(data, response, headers, config) {
                 console.log("Success Data " + response);
             })
             .error(function(data, response, headers, config) {
                 console.debug("Returned Data ");
             });
    };

例如,如果我在输入框中输入值abc@abc.com,我会看到我在表单中输入的实际值已经发送到api(self.emailData的值)。我得到200的响应。

以下是我遇到的问题,

1) 当我明确指定要发送的电子邮件地址为rq895@msstae.edu 时,为什么要发送self.emailData

2) 既然我得到了200的响应,为什么成功回调没有被触发呢。

不赞成使用成功和错误。尝试将您的代码重构为以下内容:

self.sendPost = function() {
    console.log(self.emailData); //the value I entered in the input box
    $http.get("https://api?email=rq895@msstae.edu")
    .then(function successCallback(response) {
       console.log(response)
    }, function errorCallback(response) {
       console.debug(response);
    });
};

第一个提示:请不要在控制器中有业务逻辑。在服务中移动它,并在控制器中注入服务。根据您的回答,尝试使用,然后使用和成功和错误处理程序。给出了一个例子

$http.get(URL).then(successCallback, errorCallback);
function successCallback(){
}
function errorCallback(){
}

希望这能有所帮助。

快乐学习:)