【问题标题】:Passing parameters in addition to data received from http request, to a method in angularJS除了从 http 请求接收到的数据之外,还将参数传递给 angularJS 中的方法
【发布时间】:2016-02-28 00:03:51
【问题描述】:

我的控制器中有这个方法,可以从我的 API 获取一个 json 文件。

      $scope.get = function (code) {

          api.get(code)
              .then(onJsonPart, onError);
      };

这样做:

      function onJsonPart(json) {

          console.log(json);
      }

我可以打印出收到的 JSON,但我想将多个变量传递给 onJsonPart 方法。类似的东西:

      $scope.get = function (code) {

          api.get(code)
              .then(onJsonPart(code, data), onError);
      };

这里我得到错误:数据没有明显定义,问题是我如何用接收到的数据定义数据变量。

然后为我的 onJsonPart 函数设置两个参数,如下所示:

      function onJsonPart(code, json) {

          console.log('Code: ' + code);
          console.log('json:');
          console.log(json);
      }

【问题讨论】:

  • 这是一个回调函数,它只接受一个参数,但不建议在 http 服务响应对象中添加您的自定义变量和值。

标签: angularjs json api service promise


【解决方案1】:

下面的代码会将code和API的答案res传递给onJsonPart()

  $scope.get = function (code) {

      api.get(code)
          .then(
              function(res) {
                  //...some place for logic
                  onJsonPart(code, res);
              },
              function (err) {
                  //...some place for logic
                  onError(err));
              }
      );
  };

【讨论】:

    【解决方案2】:

    试试

    api.get(code)
    .then(function (json) {
        onJsonPart(code, data);
    }, onError);
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      $scope.get = function (code) {
            api.get(code)
                .then(function(data) {
                   onJsonPart(code, data)...
                }
        };
      

      【讨论】:

        猜你喜欢
        • 2020-02-14
        • 2018-02-27
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-02
        相关资源
        最近更新 更多