如何在Javascript中将参数函数调用到$ http get方法

时间:2022-02-09 07:58:58

I'm new over here in *.

我是*中的新手。

Well I have a problem with my code and i couldn't find a solution, so I decide to ask my question here.

好吧,我的代码有问题,我找不到解决方案,所以我决定在这里问我的问题。

HTML

<body ng-app="app">
    <div ng-controller="ctrl">
    </div>

<script src="~/Scripts/angular.min.js"></script>

I included ng-app="app" in my body and I installed angularjs as well.

我在我的身体中加入了ng-app =“app”,我也安装了angularjs。

I added a javascript file in my application called ang.js

我在我的应用程序中添加了一个名为ang.js的javascript文件

ang.js

var app = angular.module('app', [])
app.controller("ctrl", function ($http) {
    $http.get("url1")
    .success(function (response){
        console.log(response);
    })
    $http.get("url2", {
        params: {
            Id: response[0].key
        }
    .success(function (response2) {
        console.log(response2);
       })
    })
    })

My question is in

我的问题在于

.success(function (response){
        console.log(response);
    })

How can i call this parameter response in the second one.

如何在第二个中调用此参数响应。

$http.get("url2", {
        params: {
            Id: response
        }

1 个解决方案

#1


1  

You need to make the second request in the success handler of the first, ie

您需要在第一个成功处理程序中发出第​​二个请求,即

var promise = $http.get('url1').then(function(res1) {
    return $http.get('url2', {
        params: {
            Id: res1.data[0].key
        }
    }).then(function(res2) {
        console.log(res2.data);
        return res2.data;
    })
});

Note that I've used then instead of the deprecated success callback.

请注意,我已使用then而不是已弃用的成功回调。

#1


1  

You need to make the second request in the success handler of the first, ie

您需要在第一个成功处理程序中发出第​​二个请求,即

var promise = $http.get('url1').then(function(res1) {
    return $http.get('url2', {
        params: {
            Id: res1.data[0].key
        }
    }).then(function(res2) {
        console.log(res2.data);
        return res2.data;
    })
});

Note that I've used then instead of the deprecated success callback.

请注意,我已使用then而不是已弃用的成功回调。