fetch.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /** PURE_IMPORTS_START tslib,_.._Observable,_.._Subscription,_.._observable_from PURE_IMPORTS_END */
  2. import * as tslib_1 from "tslib";
  3. import { Observable } from '../../Observable';
  4. import { Subscription } from '../../Subscription';
  5. import { from } from '../../observable/from';
  6. export function fromFetch(input, initWithSelector) {
  7. if (initWithSelector === void 0) {
  8. initWithSelector = {};
  9. }
  10. var selector = initWithSelector.selector, init = tslib_1.__rest(initWithSelector, ["selector"]);
  11. return new Observable(function (subscriber) {
  12. var controller = new AbortController();
  13. var signal = controller.signal;
  14. var abortable = true;
  15. var unsubscribed = false;
  16. var subscription = new Subscription();
  17. subscription.add(function () {
  18. unsubscribed = true;
  19. if (abortable) {
  20. controller.abort();
  21. }
  22. });
  23. var perSubscriberInit;
  24. if (init) {
  25. if (init.signal) {
  26. if (init.signal.aborted) {
  27. controller.abort();
  28. }
  29. else {
  30. var outerSignal_1 = init.signal;
  31. var outerSignalHandler_1 = function () {
  32. if (!signal.aborted) {
  33. controller.abort();
  34. }
  35. };
  36. outerSignal_1.addEventListener('abort', outerSignalHandler_1);
  37. subscription.add(function () { return outerSignal_1.removeEventListener('abort', outerSignalHandler_1); });
  38. }
  39. }
  40. perSubscriberInit = tslib_1.__assign({}, init, { signal: signal });
  41. }
  42. else {
  43. perSubscriberInit = { signal: signal };
  44. }
  45. fetch(input, perSubscriberInit).then(function (response) {
  46. if (selector) {
  47. subscription.add(from(selector(response)).subscribe(function (value) { return subscriber.next(value); }, function (err) {
  48. abortable = false;
  49. if (!unsubscribed) {
  50. subscriber.error(err);
  51. }
  52. }, function () {
  53. abortable = false;
  54. subscriber.complete();
  55. }));
  56. }
  57. else {
  58. abortable = false;
  59. subscriber.next(response);
  60. subscriber.complete();
  61. }
  62. }).catch(function (err) {
  63. abortable = false;
  64. if (!unsubscribed) {
  65. subscriber.error(err);
  66. }
  67. });
  68. return subscription;
  69. });
  70. }
  71. //# sourceMappingURL=fetch.js.map