简体   繁体   中英

How interceptor terminate handle Angular 4?

I have an Ionic 3 app project, I add an interceptor when the app receives a response from the server , when the response's status equals 401 then the app skip to the login page, I use app.getRootNav().setRoot(LoginPage) . However, when the page with a toast receives a 401 response, the toast will still appear, which is unexpected

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.rest = this.inj.get(RestProvider);
    return next.handle(req).do(
        res => {
        ...
        },
        err => {
            if (err instanceof HttpErrorResponse) {
                if (err.status == 401) {
                    this.app.getRootNav().setRoot(LoginPage);
                    super.showToast(this.toastCtrl, "sorry, due to authorization, you must login again")
                    return;
                } else {
                    throw err;
                }
            }
        })
}

then when my HTTP request like this:

this.http.post(this.baseUrl + "/recvUsername",param)
.subscribe(
    res => {
      this.initRecvUsernames(res["data"]);
    },
    err => {
      console.error("get receive user error:" + err.message);
      super.showToast(this.toast, "get receive user error");
    }
)

then the toast at request page will show when I skip to the login page, how to terminate the toast at request page?

You can pass a flag in http params and remove it in interceptor

const params = req.params;
const isPreventToast = params.has('preventToast');
params.delete('preventToast')
const newReq = req.clone({ params });
return next.handle(newReq).do(..., err => { if(!isPreventToast) ... })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM