简体   繁体   English

Angular 6-在应用初始化时接收HTTP GET请求

[英]Angular 6 - receive HTTP GET request on app initialization

When my Angular app is started for the first time, meaning right before the web application's pages are returned to the client's browser, I want to extract some information from the HTTP request that requested the app in the first place. 首次启动Angular应用程序时(即在Web应用程序的页面返回到客户端浏览器之前),我想从首先请求该应用程序的HTTP请求中提取一些信息。

Specifically, I want to access the headers of the HTTP request that called the angular app, from inside the angular app. 具体来说,我想从有角度的应用程序内部访问称为有角度的应用程序的HTTP请求的标头。

Is there anyway to do this in Angular 6? 无论如何,Angular 6可以做到这一点吗?

Thanks 谢谢

You can create a service that intercept the request implements the HttpInterceptor interface, you can make a clone of the request and push what you want, and then return. 您可以创建一个拦截请求的服务,该服务实现HttpInterceptor接口,可以克隆请求并推送您想要的内容,然后返回。

@Injectable() export class RequestInterceptor implements HttpInterceptor { @Injectable()导出类RequestInterceptor实现HttpInterceptor {

constructor(private tokenService: TokenService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent 
    | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {

        if(this.tokenService.hasToken()) {
            const token = this.tokenService.getToken();
            req = req.clone({
                setHeaders: {
                    'x-access-token': token
                }
            });
        }
        return next.handle(req);
}

Don't forget to declare the service in a module: 不要忘记在模块中声明服务:

providers: [{ provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }] 提供者:[{提供:HTTP_INTERCEPTORS,useClass:RequestInterceptor,多:true}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM