在AngularJS上写什么样的代码?

时间:2014-03-18 13:31:37

标签: angularjs

我正在阅读$ http的angularjs源代码,我就像:WTF?

请看这一行:https://github.com/angular/angular.js/blob/master/src/ng/http.js#L739

  promise.success = function(fn) {
    promise.then(function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

  promise.error = function(fn) {
    promise.then(null, function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

  return promise;

  function transformResponse(response) {
    // make a copy since the response must be cacheable
    var resp = extend({}, response, {
      data: transformData(response.data, response.headers, config.transformResponse)
    });
    return (isSuccess(response.status))
      ? resp
      : $q.reject(resp);
  }

return promise之后定义transformResponse函数的重点是什么?它永远不会被执行,对吧?同样在该文件中,我找到了其他地方,angularjs团队在返回语句后继续添加代码。

是否有一些魔法被扔到这里或者我只是在高处?

1 个答案:

答案 0 :(得分:2)

长话短说,如果你没有时间阅读calebboyd的链接,你可以这样做,因为

    function transformResponse(response) {...}

是一个悬挂的函数声明。

它将起作用的原因完全相同:

    mySuperSweetFunction(); // will return 'hi there'

    function mySuperSweetFunction() { return 'hi there!' }

但是如果你这样做了:

    mySuperSweetFunction(); // will throw exception.

    var mySuperSweetFunction = function() {return 'hi there'}

它不起作用,因为虽然你声明了一个函数,但你也在对一个变量进行赋值。在这种情况下,您编写通话的顺序很重要。