处理与401S 2角全球 [英] Handling 401s globally with Angular 2
问题描述
在我的角2的项目我做从返回一个可观察的服务API调用。调用code,那么支持这一观察的。例如:
In my Angular 2 project I make API calls from services that return an Observable. The calling code then subscribes to this observable. For example:
getCampaigns(): Observable<Campaign[]> {
return this.http.get('/campaigns').map(res => res.json());
}
假设服务器返回401我怎么能赶上全球的这个错误并重定向到登录页面/组件?
Let's say the server returns a 401. How can I catch this error globally and redirect to a login page/component?
感谢。
下面是我到目前为止有:
Here's what I have so far:
// boot.ts
// boot.ts
import {Http, XHRBackend, RequestOptions} from 'angular2/http';
import {CustomHttp} from './customhttp';
bootstrap(AppComponent, [HTTP_PROVIDERS, ROUTER_PROVIDERS,
new Provider(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
})
]);
// customhttp.ts
// customhttp.ts
import {Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return super.get(url, options);
}
}
我收到错误消息是backend.createConnection不是一个函数
The error message I'm getting is "backend.createConnection is not a function"
推荐答案
的观测
你从每个请求的方法得到的是类型观测与LT;响应&GT ;
。在响应
的对象,有一个状态
属性,该属性将持有 401
如果服务器返回code。所以,你可能希望它映射或转换之前检索。
The Observable
you get from each request method is of type Observable<Response>
. The Response
object, has an status
property which will hold the 401
IF the server returned that code. So you might want to retrieve that before mapping it or converting it.
如果你想避免这样的功能在每次调用可能需要延长角2的 HTTP
类,并注入自己的实现它的调用调用父(超级
)的常规 HTTP
功能,然后处理 401
错误返回对象之前。
If you want to avoid doing this functionality on each call you might have to extend Angular 2's Http
class and inject your own implementation of it that calls calls the parent's (super
) for the regular Http
functionality and then handle the 401
error before returning the object.
请参阅:
<一个href=\"https://angular.io/docs/ts/latest/api/http/Response-class.html\">https://angular.io/docs/ts/latest/api/http/Response-class.html
这篇关于处理与401S 2角全球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!