Angular - Set headers for every request

前端 未结 19 1644
[愿得一人]
[愿得一人] 2020-11-22 07:43

I need to set some Authorization headers after the user has logged in, for every subsequent request.


To set headers for a particular request,



        
19条回答
  •  囚心锁ツ
    2020-11-22 08:27

    The simplest of all

    Create a config.ts file

    import { HttpHeaders } from '@angular/common/http';
    
    export class Config {
        url: string = 'http://localhost:3000';
        httpOptions: any = {
            headers: new HttpHeaders({
               'Content-Type': 'application/json',
               'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
            })
        }
    }
    

    Then on your service, just import the config.ts file

    import { Config } from '../config';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class OrganizationService {
      config = new Config;
    
      constructor(
        private http: HttpClient
      ) { }
    
      addData(data): Observable {
         let sendAddLink = `${this.config.url}/api/addData`;
    
         return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
           tap(snap => {
          return snap;
            })
        );
     } 
    

    I think it was the simplest and the safest.

提交回复
热议问题