RxJS 6 - Angular 7 - Properly canceling current http request from subjectAngular HTTP GET with TypeScript error http.get(…).map is not a function in [null]What is the correct way to share the result of an Angular Http network call in RxJs 5?How to get current value of RxJS Subject or Observable?Angular/RxJs When should I unsubscribe from `Subscription`Remain subscribed to an RXJS subject on HTTP timeoutAngular 6 - rxjs pipe not working on valueChangesReact Rxjs: catchError doesn't return data from backendAngular RXJS CatchError in Heroes tutorialAngular/RxJS: synchronous observableHow to unsubscribe from in a switchMap called callback function in RxJS?

What was the rationale behind 36 bit computer architectures?

Is it normal practice to screen share with a client?

expansion with *.txt in the shell doesn't work if no .txt file exists

Where is this photo of a group of hikers taken? Is it really in the Ural?

Grid/table with lots of buttons

Extrapolation v. Interpolation

A planet illuminated by a black hole?

Why no ";" after "do" in sh loops?

Why are off grid solar setups only 12, 24, 48 VDC?

Strange Cron Job takes up 100% of CPU Ubuntu 18 LTS Server

Can two figures have the same area, perimeter, and same number of segments have different shape?

How to add 1 milliseconds to a datetime string?

Inadvertently nuked my disk permission structure - why?

How to judge a Ph.D. applicant that arrives "out of thin air"

How do we explain the E major chord in this progression?

How did C64 games handle music during gameplay?

How do campaign rallies gain candidates votes?

Move a group of files, prompting the user for confirmation for every file

Invert Some Switches on a Switchboard

What is the lowest speed of a bogey a jet fighter can intercept/escort?

This message is flooding my syslog, how to find where it comes from?

What should I say when a company asks you why someone (a friend) who was fired left?

Explanation for a joke about a three-legged dog that walks into a bar

High income, sudden windfall



RxJS 6 - Angular 7 - Properly canceling current http request from subject


Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null]What is the correct way to share the result of an Angular Http network call in RxJs 5?How to get current value of RxJS Subject or Observable?Angular/RxJs When should I unsubscribe from `Subscription`Remain subscribed to an RXJS subject on HTTP timeoutAngular 6 - rxjs pipe not working on valueChangesReact Rxjs: catchError doesn't return data from backendAngular RXJS CatchError in Heroes tutorialAngular/RxJS: synchronous observableHow to unsubscribe from in a switchMap called callback function in RxJS?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Hi I am having trouble with my subject subscription and my search call. I want to cancel the previous call in favor of the current one. I have search through previous threads but have not had success with finding an answer.



I know I am supposed to use switchMap() but I am not having success with it. It continues all calls regardless of state. I think it mught have to do with the way I have set things up, in that I am not returning the response I am setting it. So there is no single observable reference..?



All help is appreciated!



Please see code below:



ngOnInit() 
// I subscribe to the Subject Observable here
this._searchService.quickSearch$
.pipe(
debounceTime(1000),
distinctUntilChanged()
)
.subscribe(
// when value has changed I call runSearch
(queryString) => this.runSearch(queryString);

);



runSearch:



runSearch(searchString: any) 
this.quickSearch.runSearch(searchString).pipe(
//Not working as expected
switchMap(() =>
console.log('switchMap has bee fired');
return this.quickSearch.runSearch(searchString);
)
).subscribe(
(response) =>
// set the two way bind here
this.apiResponse = response;
,
(error) =>
console.log('ERROR!!!');
,
() =>
// this is fired when the observable is closed
console.log('I have been unsubscribed');

);



quicksearch service:



 runSearch(search: string): Observable<QuickSearch[]> 

...

return this.http.get<QuickSearch[]>(this.api.url, params: param, headers: header )
.pipe(
map((data: any) =>
return data.map((item: any[]) => this.adapter.adapt(item));

),
catchError(error => error)
);




Thanks



UPDATE



I still have not found the answer to this question. So I am going to try to rephrase it.



I have 5 parts to this:



 Input box ([])-> 
rxjs-Subject (input-text)->
runSearch(input-text) -> [ handles response ]
_service.runSearch(input-text) ->
http().get(input-text) => response


when the input box is changed then run search is called in which the search service is subscribed too this does not return










share|improve this question






























    0















    Hi I am having trouble with my subject subscription and my search call. I want to cancel the previous call in favor of the current one. I have search through previous threads but have not had success with finding an answer.



    I know I am supposed to use switchMap() but I am not having success with it. It continues all calls regardless of state. I think it mught have to do with the way I have set things up, in that I am not returning the response I am setting it. So there is no single observable reference..?



    All help is appreciated!



    Please see code below:



    ngOnInit() 
    // I subscribe to the Subject Observable here
    this._searchService.quickSearch$
    .pipe(
    debounceTime(1000),
    distinctUntilChanged()
    )
    .subscribe(
    // when value has changed I call runSearch
    (queryString) => this.runSearch(queryString);

    );



    runSearch:



    runSearch(searchString: any) 
    this.quickSearch.runSearch(searchString).pipe(
    //Not working as expected
    switchMap(() =>
    console.log('switchMap has bee fired');
    return this.quickSearch.runSearch(searchString);
    )
    ).subscribe(
    (response) =>
    // set the two way bind here
    this.apiResponse = response;
    ,
    (error) =>
    console.log('ERROR!!!');
    ,
    () =>
    // this is fired when the observable is closed
    console.log('I have been unsubscribed');

    );



    quicksearch service:



     runSearch(search: string): Observable<QuickSearch[]> 

    ...

    return this.http.get<QuickSearch[]>(this.api.url, params: param, headers: header )
    .pipe(
    map((data: any) =>
    return data.map((item: any[]) => this.adapter.adapt(item));

    ),
    catchError(error => error)
    );




    Thanks



    UPDATE



    I still have not found the answer to this question. So I am going to try to rephrase it.



    I have 5 parts to this:



     Input box ([])-> 
    rxjs-Subject (input-text)->
    runSearch(input-text) -> [ handles response ]
    _service.runSearch(input-text) ->
    http().get(input-text) => response


    when the input box is changed then run search is called in which the search service is subscribed too this does not return










    share|improve this question


























      0












      0








      0








      Hi I am having trouble with my subject subscription and my search call. I want to cancel the previous call in favor of the current one. I have search through previous threads but have not had success with finding an answer.



      I know I am supposed to use switchMap() but I am not having success with it. It continues all calls regardless of state. I think it mught have to do with the way I have set things up, in that I am not returning the response I am setting it. So there is no single observable reference..?



      All help is appreciated!



      Please see code below:



      ngOnInit() 
      // I subscribe to the Subject Observable here
      this._searchService.quickSearch$
      .pipe(
      debounceTime(1000),
      distinctUntilChanged()
      )
      .subscribe(
      // when value has changed I call runSearch
      (queryString) => this.runSearch(queryString);

      );



      runSearch:



      runSearch(searchString: any) 
      this.quickSearch.runSearch(searchString).pipe(
      //Not working as expected
      switchMap(() =>
      console.log('switchMap has bee fired');
      return this.quickSearch.runSearch(searchString);
      )
      ).subscribe(
      (response) =>
      // set the two way bind here
      this.apiResponse = response;
      ,
      (error) =>
      console.log('ERROR!!!');
      ,
      () =>
      // this is fired when the observable is closed
      console.log('I have been unsubscribed');

      );



      quicksearch service:



       runSearch(search: string): Observable<QuickSearch[]> 

      ...

      return this.http.get<QuickSearch[]>(this.api.url, params: param, headers: header )
      .pipe(
      map((data: any) =>
      return data.map((item: any[]) => this.adapter.adapt(item));

      ),
      catchError(error => error)
      );




      Thanks



      UPDATE



      I still have not found the answer to this question. So I am going to try to rephrase it.



      I have 5 parts to this:



       Input box ([])-> 
      rxjs-Subject (input-text)->
      runSearch(input-text) -> [ handles response ]
      _service.runSearch(input-text) ->
      http().get(input-text) => response


      when the input box is changed then run search is called in which the search service is subscribed too this does not return










      share|improve this question
















      Hi I am having trouble with my subject subscription and my search call. I want to cancel the previous call in favor of the current one. I have search through previous threads but have not had success with finding an answer.



      I know I am supposed to use switchMap() but I am not having success with it. It continues all calls regardless of state. I think it mught have to do with the way I have set things up, in that I am not returning the response I am setting it. So there is no single observable reference..?



      All help is appreciated!



      Please see code below:



      ngOnInit() 
      // I subscribe to the Subject Observable here
      this._searchService.quickSearch$
      .pipe(
      debounceTime(1000),
      distinctUntilChanged()
      )
      .subscribe(
      // when value has changed I call runSearch
      (queryString) => this.runSearch(queryString);

      );



      runSearch:



      runSearch(searchString: any) 
      this.quickSearch.runSearch(searchString).pipe(
      //Not working as expected
      switchMap(() =>
      console.log('switchMap has bee fired');
      return this.quickSearch.runSearch(searchString);
      )
      ).subscribe(
      (response) =>
      // set the two way bind here
      this.apiResponse = response;
      ,
      (error) =>
      console.log('ERROR!!!');
      ,
      () =>
      // this is fired when the observable is closed
      console.log('I have been unsubscribed');

      );



      quicksearch service:



       runSearch(search: string): Observable<QuickSearch[]> 

      ...

      return this.http.get<QuickSearch[]>(this.api.url, params: param, headers: header )
      .pipe(
      map((data: any) =>
      return data.map((item: any[]) => this.adapter.adapt(item));

      ),
      catchError(error => error)
      );




      Thanks



      UPDATE



      I still have not found the answer to this question. So I am going to try to rephrase it.



      I have 5 parts to this:



       Input box ([])-> 
      rxjs-Subject (input-text)->
      runSearch(input-text) -> [ handles response ]
      _service.runSearch(input-text) ->
      http().get(input-text) => response


      when the input box is changed then run search is called in which the search service is subscribed too this does not return







      angular rxjs switchmap






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 25 at 20:58







      Natdrip

















      asked Mar 26 at 16:34









      NatdripNatdrip

      4945 silver badges17 bronze badges




      4945 silver badges17 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          2














          The problem is that every time this._searchService.quickSearch$ emits you're calling runSearch method that every time creates a new chain so even when you have switchMap it makes no difference.



          Instead you should put switchMap to the first chain:



          this._searchService.quickSearch$
          .pipe(
          debounceTime(1000),
          distinctUntilChanged(),
          switchMap((searchString) => this.quickSearch.runSearch(searchString)),
          ).subscribe(
          (response) =>
          this.apiResponse = response;
          ,
          ...
          );





          share|improve this answer

























          • This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

            – Natdrip
            Mar 26 at 18:29











          • In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

            – martin
            Mar 26 at 18:52











          • The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

            – Natdrip
            Mar 26 at 20:26











          • this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

            – bryan60
            Apr 25 at 21:06











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55362084%2frxjs-6-angular-7-properly-canceling-current-http-request-from-subject%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          The problem is that every time this._searchService.quickSearch$ emits you're calling runSearch method that every time creates a new chain so even when you have switchMap it makes no difference.



          Instead you should put switchMap to the first chain:



          this._searchService.quickSearch$
          .pipe(
          debounceTime(1000),
          distinctUntilChanged(),
          switchMap((searchString) => this.quickSearch.runSearch(searchString)),
          ).subscribe(
          (response) =>
          this.apiResponse = response;
          ,
          ...
          );





          share|improve this answer

























          • This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

            – Natdrip
            Mar 26 at 18:29











          • In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

            – martin
            Mar 26 at 18:52











          • The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

            – Natdrip
            Mar 26 at 20:26











          • this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

            – bryan60
            Apr 25 at 21:06
















          2














          The problem is that every time this._searchService.quickSearch$ emits you're calling runSearch method that every time creates a new chain so even when you have switchMap it makes no difference.



          Instead you should put switchMap to the first chain:



          this._searchService.quickSearch$
          .pipe(
          debounceTime(1000),
          distinctUntilChanged(),
          switchMap((searchString) => this.quickSearch.runSearch(searchString)),
          ).subscribe(
          (response) =>
          this.apiResponse = response;
          ,
          ...
          );





          share|improve this answer

























          • This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

            – Natdrip
            Mar 26 at 18:29











          • In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

            – martin
            Mar 26 at 18:52











          • The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

            – Natdrip
            Mar 26 at 20:26











          • this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

            – bryan60
            Apr 25 at 21:06














          2












          2








          2







          The problem is that every time this._searchService.quickSearch$ emits you're calling runSearch method that every time creates a new chain so even when you have switchMap it makes no difference.



          Instead you should put switchMap to the first chain:



          this._searchService.quickSearch$
          .pipe(
          debounceTime(1000),
          distinctUntilChanged(),
          switchMap((searchString) => this.quickSearch.runSearch(searchString)),
          ).subscribe(
          (response) =>
          this.apiResponse = response;
          ,
          ...
          );





          share|improve this answer















          The problem is that every time this._searchService.quickSearch$ emits you're calling runSearch method that every time creates a new chain so even when you have switchMap it makes no difference.



          Instead you should put switchMap to the first chain:



          this._searchService.quickSearch$
          .pipe(
          debounceTime(1000),
          distinctUntilChanged(),
          switchMap((searchString) => this.quickSearch.runSearch(searchString)),
          ).subscribe(
          (response) =>
          this.apiResponse = response;
          ,
          ...
          );






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 25 at 21:08









          bryan60

          8,0931 gold badge12 silver badges25 bronze badges




          8,0931 gold badge12 silver badges25 bronze badges










          answered Mar 26 at 17:01









          martinmartin

          51.3k14 gold badges107 silver badges149 bronze badges




          51.3k14 gold badges107 silver badges149 bronze badges












          • This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

            – Natdrip
            Mar 26 at 18:29











          • In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

            – martin
            Mar 26 at 18:52











          • The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

            – Natdrip
            Mar 26 at 20:26











          • this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

            – bryan60
            Apr 25 at 21:06


















          • This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

            – Natdrip
            Mar 26 at 18:29











          • In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

            – martin
            Mar 26 at 18:52











          • The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

            – Natdrip
            Mar 26 at 20:26











          • this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

            – bryan60
            Apr 25 at 21:06

















          This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

          – Natdrip
          Mar 26 at 18:29





          This isn't working quicksearch$ is a subject so when it changes only the search string changes. when the string changes it currently calls runSearch. runSearch doesn't return anything to quick search subscribe.

          – Natdrip
          Mar 26 at 18:29













          In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

          – martin
          Mar 26 at 18:52





          In your code runSearch returns an Observable. I don’t know what you mean by “when subject changes”. You create a new subject instance on every key input?

          – martin
          Mar 26 at 18:52













          The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

          – Natdrip
          Mar 26 at 20:26





          The this._searchService.quickSearch$ is a Subject I only subscribe once. in the oninit I use this as a central service for input changes. when a change is detected that is when pass the changed value to the runSearch.

          – Natdrip
          Mar 26 at 20:26













          this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

          – bryan60
          Apr 25 at 21:06






          this is very close to being correct... you just need to do this switchMap((searchString) => this.quickSearch.runSearch(searchString)), but otherwise this answer has it right, the runSearch in your component needs to be done away with. You keep creating new subscriptions everytime you call that function so it cannot switch ever. You need to maintain a single subscription so that it can switch appropriately.

          – bryan60
          Apr 25 at 21:06









          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55362084%2frxjs-6-angular-7-properly-canceling-current-http-request-from-subject%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해