离子2当我调用安全URL时,如何重定向到登录页面



我想知道如何调用安全URL时如何重定向到登录页面,因为知道您无法将NavController注入服务

我创建了我的扩展HTTP服务:

@Injectable()
export class CustomHttp extends Http {
  constructor (backend: XHRBackend, options: RequestOptions) {
    let token = localStorage.getItem('auth_token'); 
    options.headers.set('Authorization', `Bearer ${token}`);
    super(backend, options);
  }
  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    let token = localStorage.getItem('auth_token');
    if (typeof url === 'string') { 
      if (!options) {
        // let's make option object
        options = {headers: new Headers()};
      }
      options.headers.set('Authorization', `Bearer ${token}`);
    } else {
      url.headers.set('Authorization', `Bearer ${token}`);
    }
    return super.request(url, options).catch(this.catchAuthError(this));
  }
  private catchAuthError (self: CustomHttp) {
    return (res: Response) => {
     if (res.status === 401 || res.status === 403) {
     }
      }
      return Observable.throw(res);
    };
  }
}

谢谢

我们可以在您的app.component.ts文件中使用事件:

import { Events } from 'ionic-angular';

然后确保声明事件:

public events: Events

,从组件中调用函数:

listenToEvents() {
    this.events.subscribe('user:logout', () => {
      this.nav.setRoot(LoginPage);
    });
  }

最后,您可以在您的服务中发布活动:

private catchAuthError (self: CustomHttp) {
    return (res: Response) => {
     if (res.status === 401 || res.status === 403) {
       this.events.publish('user:logout');
     }
      }
      return Observable.throw(res);
    };
  }

相关内容

  • 没有找到相关文章

最新更新