我有一个服务来处理我的 http 响应,理想情况下,我想设置它,以便每当收到 401 错误状态时,用户就会被发送到登录页面。我知道您不应该从服务中执行路由,但我希望有一种可以接受的模式,因为我想捕获所有 401。
@Injectable()
export class ResponseHandlerService implements OnInit {
options: object;
headers: any;
constructor(
private clientService: ClientService,
private globalVarService: GlobalVariablesProvider,
private toastCtrl: ToastController
private navCtrl: NavController) {
}
ngOnInit() {
this.headers = new Headers();
}
getOptions() {
return this.globalVarService.getAuthToken().subscribe( token => {
this.headers.append("authentication", token);
this.options = new RequestOptions({ headers: this.headers });
})
}
extractData(res: Response) {
let body = res.json();
return body.data || body || { };
}
private handleError = (error: Response | any) => {
let errMsg: string;
console.log("Error: ", error)
if (error instanceof Response) {
let body = error['_body'].substring(0, 200)
console.log(body)
errMsg = `${error.status} - ${error.statusText || ''} to ${error.url} - ${body}`
} else {
errMsg = error.message ? error.message : error.toString();
}
if ( error.status == 401 ) {
this.clientService.handleResponse("Invalid authentication - Please sign in again")
// does not work. states navCtrl has no provider
this.navCtrl.setRoot(LoginPage)
}
console.log(errMsg);
return Observable.throw(errMsg);
}
}
最佳答案
将“ROUTER_PROVIDERS”作为提供者传递并在您的 ResponseHandlerService 中注入(inject)路由器,然后它将起作用。
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
ResponseHandlerService
]);
关于angular - 在 Angular/Ionic 中重定向到 401 后登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48930471/