扩展Angular2 Http提供程序和处理服务器
我按照本文扩展了Http提供程序,并创建了自己的自定义Http提供程序。现在,我试图捕获所有服务器异常,并根据状态代码采取适当的操作 http.service.ts:扩展Angular2 Http提供程序和处理服务器,angular,angular2-services,angular2-http,Angular,Angular2 Services,Angular2 Http,我按照本文扩展了Http提供程序,并创建了自己的自定义Http提供程序。现在,我试图捕获所有服务器异常,并根据状态代码采取适当的操作 http.service.ts: @Injectable() export class HttpService extends Http { constructor(backend: XHRBackend, options: RequestOptions) { let token = localStorage.getItem('
@Injectable()
export class HttpService extends Http {
constructor(backend: XHRBackend, options: RequestOptions) {
let token = localStorage.getItem('auth_token'); // your custom token getter function here
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') { // meaning we have to add the token to the options, not in url
if (!options) {
// let's make option object
options = { headers: new Headers() };
}
options.headers.set('Authorization', `Bearer ${token}`);
} else {
// we have to add the token to the url object
url.headers.set('Authorization', `Bearer ${token}`);
}
return super.request(url, options).catch(this.catchAuthError(this));
}
private catchAuthError(self: HttpService) {
//I want to execute this function whenever there is any error from the server,
//but control is not coming here.
return (res: Response) => {
console.log("This is from the proxy http", res);
if (res.status === 401 || res.status === 403) {
// if not authenticated
console.log("Do something");
}
return Observable.throw(res);
};
}
}
app.module.ts:
import { HttpService } from './http.service';
@Injectable()
export class DataService {
constructor(private _http: HttpService) {
login(userName: string, password: string) {
const headers = new Headers();
headers.append("Authorization", 'Basic ' + btoa(userName + ":" + password));
headers.append("Content-Type", 'text/plain');
const requestUrl = this.loginResource + userName;
return this._http.get(requestUrl, { headers: headers })
.map((response: Response) => {
let res = response.json();
this.token = response.headers.get('token')
return res;
});
}
}
}
import { HttpService } from './services/http.service';
@NgModule({
imports: [BrowserModule, HttpModule, ...],
declarations: [...],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy },
{
provide: HttpService,
useFactory: (backend: XHRBackend, options: RequestOptions) => {
return new HttpService(backend, options);
},
deps: [XHRBackend, RequestOptions]
}
],
bootstrap: [AppComponent],
})
export class AppModule {
}
编辑:
我的自定义Http提供程序没有进行xhr调用,即使在扩展了Http之后,它仍然在调用内置的Http.request
我创建了一个,自定义Http调用在那里工作,但在我的本地代码中不工作(xhr调用工作,但内置的调用不是自定义的)。不确定本地代码中到底有什么冲突
return super.request(url, options).catch(this.catchAuthError(this));
应该是
return super.request(url, options).catch(this.catchAuthError.bind(this));
private catchAuthError (err) {
或
及
应该是
return super.request(url, options).catch(this.catchAuthError.bind(this));
private catchAuthError (err) {
将扩展类作为
useClass
值提供:
{
provide : Http,
useClass:AppHTTPInterceptor,
deps: [XHRBackend, RequestOptions, AnyOtherService]
},
AnyOtherService
不应依赖于Http
,否则会导致循环依赖错误。该服务正在执行默认的Http.request(),而不是我扩展的Http.request()。这行代码是:return super.request(url,options).catch(this.catchAuthError.bind(this));从不执行。将provide:HttpService
更改为provide:Http