jsonp.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. Zone.__load_patch('jsonp', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
  9. const noop = function() {};
  10. // because jsonp is not a standard api, there are a lot of
  11. // implementations, so zone.js just provide a helper util to
  12. // patch the jsonp send and onSuccess/onError callback
  13. // the options is an object which contains
  14. // - jsonp, the jsonp object which hold the send function
  15. // - sendFuncName, the name of the send function
  16. // - successFuncName, success func name
  17. // - failedFuncName, failed func name
  18. (Zone as any)[Zone.__symbol__('jsonp')] = function patchJsonp(options: any) {
  19. if (!options || !options.jsonp || !options.sendFuncName) {
  20. return;
  21. }
  22. const noop = function() {};
  23. [options.successFuncName, options.failedFuncName].forEach(methodName => {
  24. if (!methodName) {
  25. return;
  26. }
  27. const oriFunc = global[methodName];
  28. if (oriFunc) {
  29. api.patchMethod(global, methodName, (delegate: Function) => (self: any, args: any[]) => {
  30. const task = global[api.symbol('jsonTask')];
  31. if (task) {
  32. task.callback = delegate;
  33. return task.invoke.apply(self, args);
  34. } else {
  35. return delegate.apply(self, args);
  36. }
  37. });
  38. } else {
  39. Object.defineProperty(global, methodName, {
  40. configurable: true,
  41. enumerable: true,
  42. get: function() {
  43. return function() {
  44. const task = global[api.symbol('jsonpTask')];
  45. const target = this ? this : global;
  46. const delegate = global[api.symbol(`jsonp${methodName}callback`)];
  47. if (task) {
  48. if (delegate) {
  49. task.callback = delegate;
  50. }
  51. global[api.symbol('jsonpTask')] = undefined;
  52. return task.invoke.apply(this, arguments);
  53. } else {
  54. if (delegate) {
  55. return delegate.apply(this, arguments);
  56. }
  57. }
  58. return null;
  59. };
  60. },
  61. set: function(callback: Function) {
  62. this[api.symbol(`jsonp${methodName}callback`)] = callback;
  63. }
  64. });
  65. }
  66. });
  67. api.patchMethod(
  68. options.jsonp, options.sendFuncName, (delegate: Function) => (self: any, args: any[]) => {
  69. global[api.symbol('jsonpTask')] =
  70. Zone.current.scheduleMacroTask('jsonp', noop, {}, (task: Task) => {
  71. return delegate.apply(self, args);
  72. }, noop);
  73. });
  74. };
  75. });