ionic3 - 如何在 IONIC 3 的 Http 拦截器中使用 NavControl?

标签 ionic3

我想在 http 请求 401 错误时重定向到登录页面。我如何在 IONIC 3 中实现它。由于 IONIC 3 使用 Angular 4,这就是我不能在 HTTP 拦截器中使用任何服务的原因。

最佳答案

你可以这样做。

@Injectable()

export class Httpinterceptor implements HttpInterceptor {

    private _inProgressCount = 0;

    constructor(private event: Events) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone();
        return next
            .handle(authReq)
            .do((ev: HttpEvent<any>) => {
                if (ev instanceof HttpResponse) {
                    //HTTP Response
                }
            }, (err: any) => {
                /* HTTP ERRORRESPONSE goes here */ 
                // you can catch your http error here

                if (err.status == 401) {
                    this.event.publish('UNAUTHORIZED'); // catch the published event in app.component.ts where you define your rootPage.
                }
            });
    }
}

现在,在您的 app.component.ts 中捕获事件。

this.event.subscribe('UNAUTHORIZED', () => {
    if (this.rootPage != LoginComponent) {
        this.rootPage = LoginComponent;
    }
});

您也可以采用其他方式,例如导入 appCtrl。

this.appCtrl.getRootNavs()[0].setRoot(LoginComponent)

关于ionic3 - 如何在 IONIC 3 的 Http 拦截器中使用 NavControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49644167/

相关文章:

javascript - 在单个结果页面上显示 JSON 索引时出错

angular - 如何替换 Ionic 中的当前页面?

javascript - ionic 3 [object object] 无法解析数据

angular - 为什么 observable.subscribe 只能从构造函数中工作

angular - Ionic 3 网格无法将行项目垂直居中

Angular 形通用管道

java - 在 IONIC 3 - "ionic cordova run android"和 "ionic cordova build android"中给出错误

javascript - 如何使用 Firebase 在 Ionic 3 中通过参数检索数据

angular - ionic 无限滚动 : TypeError: Cannot read property '0' of undefined

angular - 具有自动调整大小的多个文本区域在 ionic3 中不起作用