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

          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

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현