我不太明白以下代码中以下行的约定
request.transformRequest = internal.transformRequest;
这实际上是调用internal.transformRequest
函数,还是仅将函数设置为request
对象中的同名方法?我认为它正在调用该函数,因为代码中的其他任何地方都不会调用transformRequest
,但在这种情况下data
和getHeaders
的参数如何传递?
internal.transformResourceUrl = function (url) {
if (url.substr(-1) === '/')
url = url.substr(0, url.length - 1);
return url + '.json';
};
internal.transformRequest = function (data, getHeaders) {
// If this is not an object, defer to native stringification.
if (!angular.isObject(data)) {
return (data === null) ? '' : data.toString();
}
var buffer = [];
// Serialize each key in the object.
for (var name in data) {
if (!data.hasOwnProperty(name)) continue;
var value = data[name];
buffer.push(
encodeURIComponent(name) +
'=' +
encodeURIComponent((value === null) ? '' : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer
.join('&')
.replace(/%20/g, '+')
;
return source;
};
internal.generateRequest = function (method, resource, data, account) {
method = method.toUpperCase();
if (!angular.isString(account) || account.length < 1)
account = '_default';
resource = 'Accounts/' +
accounts[account] + '/' +
internal.transformResourceUrl(resource);
var request = {
method: method,
url: apiEndpoint + resource,
headers: {
'Authorization': 'Basic ' + credentialsB64
}
};
if (method === 'POST' || method === 'PUT') {
if (data) request.data = data;
request.transformRequest = internal.transformRequest;
request.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8';
} else if (data) {
request.params = data;
}
return $http(request);
};
答案 0 :(得分:1)
&#34;这实际上是调用internal.transformRequest函数,还是只是将函数设置为等于方法&#34;
&#34;我认为它正在调用该函数,因为在代码中的其他任何地方都不会调用transformRequest&#34;
如何internal.transformRequest
方法被称为
第7行:transformRequest
:方法(函数)已添加到internal
:object
internal.transformRequest = function (data, getHeaders) {
第54行:transformRequest
request
的对象:对象已分配给上述方法
request.transformRequest = internal.transformRequest;
第59行:$http()
:使用request
调用函数:现在拥有的对象
transformRequest
:指向internal.transformRequest
return $http(request);