Search code examples
angularasp.net-core-2.0aspnetboilerplate

How to redirect to login page if aspnetboilerplate's AbpAuthorize fails in angular 4 request?


How can I redirect to login page if my requests is not authorize? Right now there is a modal telling that the user is not yet login. I've found some answers but they used MVC. Thanks.


Solution

  • you can use interceptor service to resolve this problem it will always check if any API is getting fail or not if its failing then you can redirect it to log in screen

    @Injectable()
    export class HttpInterceptor extends Http {
    public flag = false;
        constructor(
            backend: XHRBackend,
            options: RequestOptions,
            public http: Http, private router: Router, private tr:ToastrService
        ) {
            super(backend, options);
        }
    public request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
        return super.request(url, options)
            .catch(this.handleError);
    }
    
    public handleError = (error: Response) => {
    
        // Do messaging and error handling here
        const errorresponse = (<any>error)._body;
        if(localStorage.getItem('token') !== null && error.statusText) {
        if(errorresponse.toUpperCase().includes('FORBIDDEN')) {
            alert('Token is expired you need to login again');
            localStorage.clear();
            window.location.reload();
           this.router.navigateByUrl('/');
           return Observable.throw(error);
        }
    }else if(error.statusText === '' && this.flag) {
        this.tr.error('', 'Network Issue');
        this.flag = false;
    }
    }
    

    }

    add this in your each service.ts file

    constructor(private http: HttpInterceptor, private us: UserService) {}