我创建了AuthHttpProvider,它是Http包装器,允许发送GET / POST / PUT / DELETE请求并自动为每个请求添加身份验证令牌(jwt).我在所有的ionic2应用程序中使用这个包装器而不是Http.现在,当我检测到来自服务器的任何响应有403 Http错误代码时,我想注销用户(并转到loginPage).
因此,当我尝试在构造函数中注入NavController(在403检测后将其用于loginPage)
constructor (public navCtrl: NavController)
我明白了:
Uncaught (in promise): Error: No provider for NavController
如何访问Provider内的navCtrl?
这是解决方案(从
this):
原文链接:https://www.f2er.com/angularjs/140885.htmlimport { Injectable,Injector } from '@angular/core'; import { Http,Headers } from '@angular/http'; import { Observable } from "rxjs"; import 'rxjs/add/operator/map'; import { App } from "ionic-angular"; import { NavController } from "ionic-angular/index"; import { LoginPage } from "../../pages/login/login"; ... @Injectable() export class AuthHttpProvider { private navCtrl: NavController; ... constructor(public http: Http,...,private app:App ) { this.navCtrl = app.getActiveNav(); } get(url) { // http GET return this.http.get(url,this.getHeaders() ) .catch(this.globalErr(this)); } // ... http POST/PUT/DELETE private getHeaders() { ... } //(cors,csrf-token ...) private globalErr(self) { return (err) => { if ( err.status == 403 ) { self.logout(); } return Observable.throw(err); }; } public logout() { // ... this.navCtrl.setRoot(LoginPage); this.navCtrl.popToRoot; } }