How to get Request Header value when accessing my Angular application

久未见 提交于 2019-12-13 21:23:45

问题


My Angular application will be accessed from another application and the environment which is used to deploy our applications are configured in such a way that, the request coming from that application to access my Angular application will contain some information which is set in Request Header. I'm asked to use that header information to identify the application from which my Angular application is called. The other application can be either External or Internal deployed application. And that information will be available in the request header.

I'm not able to find any way on how to get/read header information of the my application access request in Angular. Somebody please help me..


回答1:


because there is no method to do this. Your Application is running in the browser, so your application doesnt receive any requests, but the browser does. You should probably find another architecture. Involve your backend in the flow. Maybe construct an endpoint which is redirecting to your application.

Another same question

So the only way I know to retrieve anything from the headers is the httpInterceptor, that is intercepting any outgoing request and is observing the response like so:

import { Injectable } from '@angular/core';
import { HttpInterceptor, 
         HttpEvent, 
         HttpHandler, 
         HttpRequest, 
         HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

   constructor(private userService: UserService, 
               private constantsService: ConstantsService){ }

public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if(req.url.includes(/*whatever you are looking for*/)) { 

    }

    return next.handle(req).do((suc) => {
        if(suc.type !== 0){
            const whateverDataYouNeed = suc['headers'].get(/*whatever header you need*/);
            // Do something with it           
        }

    }).
    catch((error, caught) => {
        return Observable.throw(error);
    }) as any;
  }
}

Best regards!



来源:https://stackoverflow.com/questions/51984914/how-to-get-request-header-value-when-accessing-my-angular-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!