如何在 http header 中为令牌设置变量

How to set up a variable for a token In http header

我有一个休息电话,并在我的服务中创建了一个 header。我现在面临的问题是,60 分钟后,我的令牌过期,我必须手动更改代码中的令牌。

我正在尝试设计一个文本框,用户只需在其中输入新的令牌,然后通过单击按钮,调用令牌分配的变量并显示来自我的 API 的数据。

我已经创建了一个文本框和按钮,但我不确定如何将变量分配给我的授权令牌的逻辑。并将它们分配给我的按钮。

我在互联网上寻找资源。但是它们有点复杂。我对此很陌生,期待一个简单的解决方案。谢谢你。

这是我到目前为止尝试过的方法。

Authenticate.html

<p>Please enter a valid token</p>
<input  #tokens
  (keyup.enter)="addtoken(tokens.value)"
       (blur)="addtoken(tokens.value); tokens.value = ''">

<button (click)="addtoken(tokens.value)">Send Request</button>

<ul><li *ngFor="let token of tokens">{{token}}</li> </ul>

这是我的 service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";



const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Bearer  bafhejfbewfwlejfwfwe'
  })
};

@Injectable({
  providedIn: 'root'
})


export class DataService {

  constructor(private http: HttpClient) { }

  getlocations() {
    return this.http.get(
      'url' , httpOptions)
  }

}

只需在您的服务中创建一个方法(updateHeader(updatedHeader))来更新 header 并从您的组件中调用它:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class DataService {

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'Bearer  bafhejfbewfwlejfwfwe'
    })
  };

  constructor(private http: HttpClient) { }

  updateHeader(updatedHeader) {
    this.httpOptions.headers = this.httpOptions.headers.set('Authorization', `Bearer ${updatedHeader}`);
    console.log(this.httpOptions.headers.get('Authorization'));
  }

  getlocations() {
    console.log(this.httpOptions.headers.get('Authorization'));
    return this.http.get('url' , this.httpOptions);
  }

}

然后你可以在你的组件中调用这个方法:

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  tokens = [];

  constructor(private dataService: DataService) {}

  addtoken(value) {
    if (value) {
      this.tokens.push(value);
      this.dataService.updateHeader(value);
    }
  }
}

Here's a Working Sample StackBlitz for your ref.