zone-patch-jsonp.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2022 Google LLC. https://angular.io/
  5. * License: MIT
  6. */
  7. Zone.__load_patch('jsonp', (global, Zone, api) => {
  8. // because jsonp is not a standard api, there are a lot of
  9. // implementations, so zone.js just provide a helper util to
  10. // patch the jsonp send and onSuccess/onError callback
  11. // the options is an object which contains
  12. // - jsonp, the jsonp object which hold the send function
  13. // - sendFuncName, the name of the send function
  14. // - successFuncName, success func name
  15. // - failedFuncName, failed func name
  16. Zone[Zone.__symbol__('jsonp')] = function patchJsonp(options) {
  17. if (!options || !options.jsonp || !options.sendFuncName) {
  18. return;
  19. }
  20. const noop = function () { };
  21. [options.successFuncName, options.failedFuncName].forEach(methodName => {
  22. if (!methodName) {
  23. return;
  24. }
  25. const oriFunc = global[methodName];
  26. if (oriFunc) {
  27. api.patchMethod(global, methodName, (delegate) => (self, args) => {
  28. const task = global[api.symbol('jsonTask')];
  29. if (task) {
  30. task.callback = delegate;
  31. return task.invoke.apply(self, args);
  32. }
  33. else {
  34. return delegate.apply(self, args);
  35. }
  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 delegate = global[api.symbol(`jsonp${methodName}callback`)];
  46. if (task) {
  47. if (delegate) {
  48. task.callback = delegate;
  49. }
  50. global[api.symbol('jsonpTask')] = undefined;
  51. return task.invoke.apply(this, arguments);
  52. }
  53. else {
  54. if (delegate) {
  55. return delegate.apply(this, arguments);
  56. }
  57. }
  58. return null;
  59. };
  60. },
  61. set: function (callback) {
  62. this[api.symbol(`jsonp${methodName}callback`)] = callback;
  63. }
  64. });
  65. }
  66. });
  67. api.patchMethod(options.jsonp, options.sendFuncName, (delegate) => (self, args) => {
  68. global[api.symbol('jsonpTask')] =
  69. Zone.current.scheduleMacroTask('jsonp', noop, {}, (task) => {
  70. return delegate.apply(self, args);
  71. }, noop);
  72. });
  73. };
  74. });