当前位置: 代码迷 >> JavaScript >> 同步通话
  详细解决方案

同步通话

热度:100   发布时间:2023-06-06 09:43:16.0

我有一个Web应用程序,其中我的应用程序的前端使用有角js。 我在angular js控制器中有一个方法,称为“单击按钮”。 在这种方法中,我调用了角度服务以将请求发送到Java控制器。 逻辑看起来像这样

var submitted= true;

submitted= sampleService.sampleMethod(sampleParam);
alert(submitted);
if(!submitted){
    //some action
}

如果请求成功,则该服务将返回true;如果请求失败,则将返回false。 我遇到的问题是我在发送请求之前收到了警报(警报说未定义)。 因此,无论响应如何,if条件都会失败。

这个问题有解决方案吗?

编辑:

样品方法

this.sampleMethod = function (sampleServiceMethod, obj){

        var modalInstance = $modal.open({

              templateUrl: 'example.html',
              controller: 'anotherController',
              resolve: {
                modalServiceMethod: function () {
                  return sampleServiceMethod;
                }
              }
            });

        modalInstance.result.then(function (modalServiceMethod) {
            modalServiceMethod(obj).then(function(response){
                $window.location = response.sampleUrl;
            }, function(err) {
                $log.error("error occured", err);
            });
         }, function () {
            $log.debug('error on: ' + new Date());
         }).finally(function() {
                return false;
         });

    };

基本上,如果请求成功,页面将被重定向。 但是我需要失败期间的false返回值来进行必要的更改。

**更新#1 **如果您稍微组织一下并重命名代码,我会更好地帮助您。 当它们没有任何含义时,很难用所有名字来跟随。

首先,请尝试在modalInstance之前添加以下return语句:

return modalInstance.result.then(function (modalServiceMethod) {
            modalServiceMethod(obj).then(function(response){
                $window.location = response.sampleUrl;
            }, function(err) {
                $log.error("error occured", err);
            });
         }, function () {
            $log.debug('error on: ' + new Date());
         }).finally(function() {
                return false;
         });

**原始答案**

为什么要声明Submit为true,然后在其上运行run函数?

看起来像这样的功能:

sampleService.sampleMethod(sampleParam);

返回未定义。

添加该函数的代码,以便我们对其进行研究。

如果该函数将请求发送到服务器以获取数据,则它将作为承诺返回。 在这种情况下,您的代码应为:

    sampleService.sampleMethod(sampleParam).then(function(response){ 
      submitted = response.data;
      conole.log(submitted)
    });

但是您在警报中而不是在Promise对象中未定义的事实表明您可能错过了sampleService.sampleMethod(sampleParam)方法中的“ return”语句。 该方法应如下所示:

function sampleMethod(param) { 
  return $http.get('url', param)
}
  相关解决方案