Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi I'm stuck with simple issue.

The objective for my code is to handle 401 http response and navigate back to login screen.

The following is my base class

@Injectable({
  providedIn: 'root',
})
export class BaseService {
  constructor(public router: Router, public snakeBar: MatSnackBar) {}

  handleError(errorResponse: HttpErrorResponse) {
    if (errorResponse instanceof HttpErrorResponse) {
      if (errorResponse.status == 401) {
    this.router.navigate(['auth/login']);
    this.snakeBar.open('Session expired, Please login again', 'OK', {
      duration: 3000,
    });
      }
    }
    }
    }

The following is one of the service which extends the base service.

@Injectable({
  providedIn: 'root',
})
export class SettingsService extends BaseService {
  constructor(
    private https: HttpClient
  ) {
    super();
  }

  getSomeData(): Observable<any> {
    const { ctoken } = localStorage;
    const httpOptions = {
      headers: new HttpHeaders({
        Authorization: `bearer ${ctoken}`,
      }),
    };

    return this.https
      .get(
        `someUrl`,
        httpOptions
      )
      .pipe(catchError(this.handleError));
  }
  }

As per code standard i have to send two parameter to my parent, both router and snack bar.

1st issue = Im extending the base serive in 10+ service, it's difficult to send from all extended class. 2nd issue = Even after sending super(router, matSnackBar). Im getting error router and snackbar is undefined in base service.

Can anybody explain how to solve this issue.

Im using angular 10


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

Handling backend 401 Unauthorized

Every page of our application makes several XHR calls to the backend. At some point or other, for various reasons, the user's session may expire. Instead of showing the user a pile of error messages - at first sign of trouble (401) we redirect the user to the login page.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  request = request.clone({
    setHeaders: {
      'my-auth-token': `${this.getSessionToken()}`
    }
  });
  return next.handle(request).pipe(
    catchError((response: HttpErrorResponse) => {
      if (response.status === 401) {
        // Do something here
      }
      return throwError(response);
    }
  );
}

For more info check this post or this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...