rsi*_*dia 2 rxjs angular-http-interceptors angular5
嗨,我是angular 5的新手,并跟着一些博客写了HTTP拦截器.
export class AngularInterceptor implements HttpInterceptor {
public http404 = false;
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
// Clone the request to add the new header.
const httpReq = req.clone(
{
headers: req.headers.set("headerName", "headerValue")
}
);
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(httpReq)
.catch((error, caught) => {
//intercept the respons error and displace it to the console
console.log("Error Occurred");
if(error.status === 404)
this.http404 = true;
//need to pass this value to another component. Let's say app.component.ts and display some message to the user.
//return the error to the method that called it
return Observable.throw(error);
}) as any;
}
Run Code Online (Sandbox Code Playgroud)
}
这工作正常.但我需要做的是将此错误代码传递给其他组件,并在屏幕上为用户打印一条消息.一个人要做的就是创建一个可观察的但我无法实现它.
任何帮助都非常感谢.
您可以通过利用a来使用服务来实现这一目标Subject.这是一个使用的例子BehaviourSubject.
首先,您创建一个服务.这项服务将在两个类中共享:
export class BroadcastService {
public http404: BehaviorSubject<boolean>;
constructor() {
//initialize it to false
this.http404 = new BehaviorSubject<boolean>(false);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的HttpInterceptor课堂上,你注入了BroadcastService它.要更新BehvaiourSubject,只需使用.next():
export class AngularInterceptor implements HttpInterceptor {
public http404 = false;
constructor(public broadcastService: BroadcastService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
// Clone the request to add the new header.
const httpReq = req.clone({
headers: req.headers.set("headerName", "headerValue")
});
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(httpReq)
.catch((error, caught) => {
//intercept the respons error and displace it to the console
console.log("Error Occurred");
if (error.status === 404)
this.http404 = true;
//need to pass this value to another component. Let's say app.component.ts and display some message to the user.
this.broadcastService.http404.next(true);
//return the error to the method that called it
return Observable.throw(error);
}) as any;
}
}
Run Code Online (Sandbox Code Playgroud)
在你的app.component.ts,只需使用订阅.asObservable().你也需要注入它:
export class AppComponent implements ngOnInit {
constructor(public broadCastService: BroadcastService) {
}
OnInit() {
this.broadCastService.http404.asObservable().subscribe(values => {
console.log(value)//will return false if http error
})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2880 次 |
| 最近记录: |