title: Angular router.navigate not working after 403 error
body: <h2>Brief description</h2>
  
  <p>In my application, there are 100s courses and a user has access to few of them only. If he clicks on others, he gets 403 error. The moment he clicks on restricted course, from there all other navigation fails (even to the course he has access) and <a href="https://angular.io/api/router/Router#navigate" rel="nofollow noreferrer">router.navigate resolves to 'false'</a>. That is on click event, router.navigate does not work and emits NavigationCancel only.</p>
  
  <p>Angular-7</p>
  
  <hr>
  
  <h2>Pattern of error</h2>
  
  <ol>
  <li>I have search box and i use material input and <a href="https://material.angular.io/components/autocomplete/examples" rel="nofollow noreferrer">material autocomplete</a> to list courses as user types.</li>
  <li>search for course <strong>Angular</strong> (allowed), click on 1st result, <strong>successfully navigates</strong> to <code>/Course/499</code></li>
  <li>search for course <strong>React</strong> (restricted course), click on 1st result, so <strong>show 403 error</strong>. <code>/course/78</code> (403 error)</li>
  <li>again search for <strong>Angular</strong>, click on 1st result, but <strong>does not navigate now</strong>.</li>
  </ol>
  
  <hr>
  
  <h2>Code</h2>
  
  <p><em>COURSE.COMP.HTML</em>
  <div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form class="search-form" *ngIf="cardsLoaded"&gt;
      &lt;mat-form-field appearance="fill"&gt;
        &lt;mat-label&gt;Search courses&lt;/mat-label&gt;
        &lt;input
          matInput
          placeholder="eg. angular"
          name="search"
          autocomplete="off"
          #searchInput
          [formControl]="searchBox"
          [matAutocomplete]="auto"
        /&gt;
        &lt;mat-autocomplete
          #auto="matAutocomplete"
          [displayWith]="displayFn"
          (optionSelected)="loadCourse($event.option.value.id)"  // FUNCTION TO NAVIGATE
        &gt;
          &lt;mat-option *ngIf="flag.searching"&gt;Searching Courses...&lt;/mat-option&gt;
          &lt;mat-option *ngFor="let course of list" [value]="course"&gt;
            &lt;span class="option"&gt;
              &lt;span
                class="{{ course.course_status }}"
                [innerHTML]="course.name | highlight: searchInput.value"
              &gt;&lt;/span&gt;
              &lt;i&gt; {{ course.course_status }} &lt;/i&gt;
            &lt;/span&gt;
          &lt;/mat-option&gt;
        &lt;/mat-autocomplete&gt;
        &lt;mat-icon matSuffix&gt;search&lt;/mat-icon&gt;
      &lt;/mat-form-field&gt;
    &lt;/form&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>COURSE.COMP.TS</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>/**
   * Redirects user to the course page
   * @param id course id
   */
  loadCourse(id: number) {
    console.log(`--------------LOADING COURSE (${id})---------------`); // i am getting correct courseId on every click
    this.router.navigate([`/Course/${id}`]).then(nav =&gt; {
      console.log('Yayy', nav); // true if navigation is successful
    }, err =&gt; {
      console.log('Navigation Failed', err) // when there's an error
      // this returns flase everytime, after clicking on a restricted course.
    });
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>Guards</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>export class AuthGuard implements CanActivate {
    constructor(
      private router: Router,
      private authService: AuthService,
      private store: Store&lt;State&gt;
    ) {}
  
    canActivate(
      next: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
    ): Observable&lt;boolean&gt; {
      return this.authService.getProfile().pipe(
        map(
          // if success return true
          data =&gt; {
            this.store.dispatch(new fromCat.StoreProfile(data));
            return true;
          }
        ),
        // if failur return false, and redirect to login page
        catchError(err =&gt; {
          this.router.navigate(["/login"]);
          return of(false);
        })
      );
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>TokenInterceptor</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>export class TokenInterceptorService implements HttpInterceptor {
    constructor(
      private authService: AuthService,
      private router: Router,
      private snackbar: MatSnackBar,
      private store: Store&lt;State&gt;
    ) {}
  
    intercept(
      req: HttpRequest&lt;any&gt;,
      next: HttpHandler
    ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
      const token = this.authService.getApi();
      let clonedReq;
  
      return next.handle(clonedReq).pipe(
        // if api call returns any error, show details in console and redirect to appropriate page
        tap(
          (event: HttpEvent&lt;any&gt;) =&gt; {},
          (err: any) =&gt; {
            if (err instanceof HttpErrorResponse) {
              ////////// ERROR 404 - REDIRECT //////////
              if (err.status === 404) {
                console.log(
                  "%cError in making HTTP request",
                  "color: #FF0088; background: #222; font-size: 24px",
                  err,
                  clonedReq
                );
                this.router.navigate(["/notfound"]);
              }
  
              ////////// ERROR 403 - SNACKBAR //////////
              if (err.status === 403) {
                console.log('error');
                this.snackbar.open(`You do not have required permissions to perform the action. Please contact admin.`);
              }
  
              ////////// ERROR 401 - REDIRECT //////////
              if (err.status === 401) {
                this.router.navigate(["/login"]);
              }
  
              ////////// ERROR 400 - SNACKBAR //////////
              if (err.status === 400) {
                this.snackbar.open(`${err.error.error}`);
              }
  
              ////////// ERROR 500 - SNACKBAR //////////
              if (err.status === 500) {
                console.log(
                  "%cError: 500 \n",
                  "color: #FF0088; background: #222; font-size: 24px",
                  err
                );
                this.snackbar.open(`${err.status} - ${err.error.error}`);
              }
            }
          }
        )
      );
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <hr>
  
  <h2>DEBUGGING</h2>
  
  <ul>
  <li><a href="https://github.com/angular/angular/issues/15946#issuecomment-330892071" rel="nofollow noreferrer">ngZone</a> - not sure where to exactly keep this code piece</li>
  <li><p>checked router Events, it emits NavigationCancel everytime after user clicks on restricted course.</p>
  
  <pre><code>this.router.events
  .pipe(filter(e =&gt; e instanceof RouterEvent))
  .subscribe((event) =&gt; {
      console.log('routerEvent =&gt;', event);     
  });
  </code></pre></li>
  </ul>
  
  <hr>
  
  <h2>Screenshots</h2>
  
  <ol>
  <li>searching course with id=499, (could navigate)
  <a href="https://i.stack.imgur.com/TQRdV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TQRdV.jpg" alt="navigate working fine"></a></li>
  <li>search other course (restricted to user, id=78) and click on it. should not navigate as expected.
  <a href="https://i.stack.imgur.com/hGzb5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGzb5.jpg" alt="searching react"></a></li>
  <li>Gives 403 error as expected. so fine till now
  <a href="https://i.stack.imgur.com/ZHVq8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHVq8.jpg" alt="gives 403 error in console (expected)"></a></li>
  <li>search and try navigating to course/499. could not nagivate.
  <a href="https://i.stack.imgur.com/Qx6P2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qx6P2.jpg" alt="router resolves to false"></a></li>
  </ol>
  
  <hr>
  
  <p>Please suggest what could be the solution. I am not sure why router is behaving like this and how to force navigate it.</p>