Prevent Error to be shown to the user after subscribe block The Next CEO of Stack Overflowangular2 with Slim framework jwt authenticationAngular2 login service jwt tokenHttpInterceptor and AuthGuard are blocking each otherAngular http requestAngular 6 Error using RxJS: Cannot read property 'call' of undefinedAngular 6 & RxJS 6 Breaking ChangesHttpInterceptor detect 401 responsesHow can I prevent the Angular 6 Custom-Reuse-Strategy from caching a 403 forbidden page?Http response is detected but view is not updated using Angular 6.xAngular intercepting http errors

Compilation of a 2d array and a 1d array

Incomplete cube

What did the word "leisure" mean in late 18th Century usage?

Is this a new Fibonacci Identity?

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

Simplify trigonometric expression using trigonometric identities

Why can't we say "I have been having a dog"?

Why doesn't Shulchan Aruch include the laws of destroying fruit trees?

"Eavesdropping" vs "Listen in on"

Planeswalker Ability and Death Timing

What happens if you break a law in another country outside of that country?

How to unfasten electrical subpanel attached with ramset

Can Sri Krishna be called 'a person'?

Oldie but Goldie

How to show a landlord what we have in savings?

Is it OK to decorate a log book cover?

Can you teleport closer to a creature you are Frightened of?

Find a path from s to t using as few red nodes as possible

Salesforce opportunity stages

How to pronounce fünf in 45

pgfplots: How to draw a tangent graph below two others?

Read/write a pipe-delimited file line by line with some simple text manipulation

Creating a script with console commands

Cannot restore registry to default in Windows 10?



Prevent Error to be shown to the user after subscribe block



The Next CEO of Stack Overflowangular2 with Slim framework jwt authenticationAngular2 login service jwt tokenHttpInterceptor and AuthGuard are blocking each otherAngular http requestAngular 6 Error using RxJS: Cannot read property 'call' of undefinedAngular 6 & RxJS 6 Breaking ChangesHttpInterceptor detect 401 responsesHow can I prevent the Angular 6 Custom-Reuse-Strategy from caching a 403 forbidden page?Http response is detected but view is not updated using Angular 6.xAngular intercepting http errors










0















I am kinda new at Angular, I build small PoC but I am missing some points before I move, is there any way to make this code synchronous?
What I mean by this is that until you have no response from the User method which calls REST API, what I want in my ErrorInterceptor is that...



Once someone login to the web correctly, he is moved to the home page, and token (User object) is stored in localStorage, so after user came back in a next day the REST token is already expired, so I implemented refresh token methodology and once someone will navigate to any page he basically fetch data via REST API in the background, to do this he need a new token, so method this.userService.refreshToken(currentUser) to refresh the token and update the one that is stored for User, everything looks good in this code but I need to somehow prevent Error to not be shown to user (as the token is refreshed in the meantime and next calls will work just fine).



If I wanted to return the "throwError" in the subscribe block, it did not work at all, it does return error in the end, so is there any chance to restrict to not show the error if token is refreshed and it is valid one now?



import Injectable from '@angular/core';
import HttpRequest, HttpHandler, HttpEvent, HttpInterceptor from '@angular/common/http';
import Observable, throwError from 'rxjs';
import catchError, first, tap from 'rxjs/operators';

import AuthenticationService, UserService from '@/_services';
import rejects from "assert";
@Injectable()
export class ErrorInterceptor implements HttpInterceptor
constructor(private authenticationService: AuthenticationService, private userService: UserService)


intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
let currentUser = this.authenticationService.currentUserValue;
return next.handle(request).pipe(
catchError(err =>
console.log(JSON.stringify(err));
if (err.status === 401 && !location.pathname.includes('/login'))
if (err.error.message && err.error.message.toString().includes("Not authorized!") && currentUser.refreshToken)
this.userService.refreshToken(currentUser)
.pipe(first())
.subscribe(
data =>
currentUser.token = data['token'];
return next.handle(request);
, error =>
this.authenticationService.logout();
location.reload(true);//

)


return throwError(JSON.stringify(err.error));

))











share|improve this question




























    0















    I am kinda new at Angular, I build small PoC but I am missing some points before I move, is there any way to make this code synchronous?
    What I mean by this is that until you have no response from the User method which calls REST API, what I want in my ErrorInterceptor is that...



    Once someone login to the web correctly, he is moved to the home page, and token (User object) is stored in localStorage, so after user came back in a next day the REST token is already expired, so I implemented refresh token methodology and once someone will navigate to any page he basically fetch data via REST API in the background, to do this he need a new token, so method this.userService.refreshToken(currentUser) to refresh the token and update the one that is stored for User, everything looks good in this code but I need to somehow prevent Error to not be shown to user (as the token is refreshed in the meantime and next calls will work just fine).



    If I wanted to return the "throwError" in the subscribe block, it did not work at all, it does return error in the end, so is there any chance to restrict to not show the error if token is refreshed and it is valid one now?



    import Injectable from '@angular/core';
    import HttpRequest, HttpHandler, HttpEvent, HttpInterceptor from '@angular/common/http';
    import Observable, throwError from 'rxjs';
    import catchError, first, tap from 'rxjs/operators';

    import AuthenticationService, UserService from '@/_services';
    import rejects from "assert";
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor
    constructor(private authenticationService: AuthenticationService, private userService: UserService)


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
    let currentUser = this.authenticationService.currentUserValue;
    return next.handle(request).pipe(
    catchError(err =>
    console.log(JSON.stringify(err));
    if (err.status === 401 && !location.pathname.includes('/login'))
    if (err.error.message && err.error.message.toString().includes("Not authorized!") && currentUser.refreshToken)
    this.userService.refreshToken(currentUser)
    .pipe(first())
    .subscribe(
    data =>
    currentUser.token = data['token'];
    return next.handle(request);
    , error =>
    this.authenticationService.logout();
    location.reload(true);//

    )


    return throwError(JSON.stringify(err.error));

    ))











    share|improve this question


























      0












      0








      0








      I am kinda new at Angular, I build small PoC but I am missing some points before I move, is there any way to make this code synchronous?
      What I mean by this is that until you have no response from the User method which calls REST API, what I want in my ErrorInterceptor is that...



      Once someone login to the web correctly, he is moved to the home page, and token (User object) is stored in localStorage, so after user came back in a next day the REST token is already expired, so I implemented refresh token methodology and once someone will navigate to any page he basically fetch data via REST API in the background, to do this he need a new token, so method this.userService.refreshToken(currentUser) to refresh the token and update the one that is stored for User, everything looks good in this code but I need to somehow prevent Error to not be shown to user (as the token is refreshed in the meantime and next calls will work just fine).



      If I wanted to return the "throwError" in the subscribe block, it did not work at all, it does return error in the end, so is there any chance to restrict to not show the error if token is refreshed and it is valid one now?



      import Injectable from '@angular/core';
      import HttpRequest, HttpHandler, HttpEvent, HttpInterceptor from '@angular/common/http';
      import Observable, throwError from 'rxjs';
      import catchError, first, tap from 'rxjs/operators';

      import AuthenticationService, UserService from '@/_services';
      import rejects from "assert";
      @Injectable()
      export class ErrorInterceptor implements HttpInterceptor
      constructor(private authenticationService: AuthenticationService, private userService: UserService)


      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
      let currentUser = this.authenticationService.currentUserValue;
      return next.handle(request).pipe(
      catchError(err =>
      console.log(JSON.stringify(err));
      if (err.status === 401 && !location.pathname.includes('/login'))
      if (err.error.message && err.error.message.toString().includes("Not authorized!") && currentUser.refreshToken)
      this.userService.refreshToken(currentUser)
      .pipe(first())
      .subscribe(
      data =>
      currentUser.token = data['token'];
      return next.handle(request);
      , error =>
      this.authenticationService.logout();
      location.reload(true);//

      )


      return throwError(JSON.stringify(err.error));

      ))











      share|improve this question
















      I am kinda new at Angular, I build small PoC but I am missing some points before I move, is there any way to make this code synchronous?
      What I mean by this is that until you have no response from the User method which calls REST API, what I want in my ErrorInterceptor is that...



      Once someone login to the web correctly, he is moved to the home page, and token (User object) is stored in localStorage, so after user came back in a next day the REST token is already expired, so I implemented refresh token methodology and once someone will navigate to any page he basically fetch data via REST API in the background, to do this he need a new token, so method this.userService.refreshToken(currentUser) to refresh the token and update the one that is stored for User, everything looks good in this code but I need to somehow prevent Error to not be shown to user (as the token is refreshed in the meantime and next calls will work just fine).



      If I wanted to return the "throwError" in the subscribe block, it did not work at all, it does return error in the end, so is there any chance to restrict to not show the error if token is refreshed and it is valid one now?



      import Injectable from '@angular/core';
      import HttpRequest, HttpHandler, HttpEvent, HttpInterceptor from '@angular/common/http';
      import Observable, throwError from 'rxjs';
      import catchError, first, tap from 'rxjs/operators';

      import AuthenticationService, UserService from '@/_services';
      import rejects from "assert";
      @Injectable()
      export class ErrorInterceptor implements HttpInterceptor
      constructor(private authenticationService: AuthenticationService, private userService: UserService)


      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
      let currentUser = this.authenticationService.currentUserValue;
      return next.handle(request).pipe(
      catchError(err =>
      console.log(JSON.stringify(err));
      if (err.status === 401 && !location.pathname.includes('/login'))
      if (err.error.message && err.error.message.toString().includes("Not authorized!") && currentUser.refreshToken)
      this.userService.refreshToken(currentUser)
      .pipe(first())
      .subscribe(
      data =>
      currentUser.token = data['token'];
      return next.handle(request);
      , error =>
      this.authenticationService.logout();
      location.reload(true);//

      )


      return throwError(JSON.stringify(err.error));

      ))








      angular typescript error-handling






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 21 at 21:13









      georgeawg

      34.4k115370




      34.4k115370










      asked Mar 21 at 20:00









      WinterTimeWinterTime

      689




      689






















          0






          active

          oldest

          votes












          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%2f55288411%2fprevent-error-to-be-shown-to-the-user-after-subscribe-block%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          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%2f55288411%2fprevent-error-to-be-shown-to-the-user-after-subscribe-block%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript