简体   繁体   English

角度链接AJAX调用

[英]Angular chaining AJAX calls

I have to do 2 AJAX calls. 我必须做2个AJAX调用。 Second one depends on the first call result. 第二个取决于第一个呼叫结果。 Right now I do it like this: 现在我这样做:

Service.getA(car).then(function(carInfo) {
    if (carInfo.success) {
        Service.getB(carInfo.number).then(function(holderInfo) {
            console.log(holderInfo);
        });
    }
});

Service: 服务:

getA: function(car) {
    return Server.execute({
        method: 'GET',
        url: 'a/a',
        params: {
            car: car
        },
    }).then(function (carInfo) {
        return carInfo;
    });
},

getB method is analogous - just another URL and another parameters. getB方法是类似的 - 只是另一个URL和另一个参数。 I am learning angular and want to implement this code using promises and defers (google suggest that code will be more beautoful). 我正在学习角度,并希望使用promises和defers实现此代码(谷歌建议代码将更beautoful)。 How can I do that? 我怎样才能做到这一点?

The way you've done it is typically how you chain ajax calls though you can simplify this a bit: 你完成它的方式通常是如何链接ajax调用,虽然你可以简化这一点:

  Service.getA(car).then(function(carInfo) {
     Service.getB(carInfo.number).then(function(holderInfo) {
        console.log(holderInfo);
     });
  });

For errors have your server return Bad Request 400 and then you can chain the .error() callback instead of determining success based on the success property. 对于错误,您的服务器返回Bad Request 400,然后您可以链接.error()回调,而不是根据success属性确定成功。

As Cerbrus pointed out, $q.all([promise1, promise2]) executes them in parallel instead of one depending on the other. 正如Cerbrus指出的那样, $q.all([promise1, promise2])并行执行它们,而不是依赖于另一个。

Your getA method should just return the promise itself like so: 你的getA方法应该像这样返回promise本身:

 getA: function(car) {
    return Server.execute({
       method: 'GET',
       url: 'a/a',
       params: {
           car: car
       },
    });
  }

If you really need to bind the extra callback from within the service you can do this: 如果你真的需要从服务中绑定额外的回调,你可以这样做:

 getA: function(car) {
    return Server.execute({
        method: 'GET',
        url: 'a/a',
        params: {
            car: car
        },
    }).then(function (carInfo) {
        //do something?

    }, function () {
        //handle error?
    });
},

As you've said both are similar except url, parameters I'd go with 正如你所说的那样两者都是相似的,除了url,我会选择参数

request : function(url, params) {
    return Server.execute({
        method: 'GET',
        url: url,
        params: params,
    });
},

call it 叫它

Service.request('a/a', param).then(function(carInfo) {
    if (carInfo.success) {
        Service.request('b/b', carInfo.number).then(function(holderInfo) {
            console.log(holderInfo);
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM