在Angular中,如果授权头部为空,可能是因为在请求中未正确设置授权头部。
以下是一个解决方案的示例代码:
AuthService服务,用于处理授权逻辑。import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = 'http://your-api-url';
  constructor(private http: HttpClient) { }
  login(username: string, password: string) {
    return this.http.post(`${this.apiUrl}/login`, { username, password });
  }
  getAuthenticatedData() {
    const token = localStorage.getItem('token');
    const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
    return this.http.get(`${this.apiUrl}/data`, { headers });
  }
}
  
AuthService的login方法来获取授权令牌。import { Component } from '@angular/core';
import { AuthService } from 'path-to-auth-service';
@Component({
  selector: 'app-login',
  template: `
    
  `,
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  username: string;
  password: string;
  constructor(private authService: AuthService) { }
  login() {
    this.authService.login(this.username, this.password).subscribe(
      data => {
        localStorage.setItem('token', data.token);
        // Redirect to authenticated page
      },
      error => {
        console.error(error);
      }
    );
  }
}
AuthService的getAuthenticatedData方法来获取授权数据。import { Component, OnInit } from '@angular/core';
import { AuthService } from 'path-to-auth-service';
@Component({
  selector: 'app-data',
  template: `
    {{ data }}
  `,
  styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
  data: any;
  constructor(private authService: AuthService) { }
  ngOnInit() {
    this.authService.getAuthenticatedData().subscribe(
      data => {
        this.data = data;
      },
      error => {
        console.error(error);
      }
    );
  }
}
通过以上代码示例,可以在Angular中正确设置授权头部,解决授权头部为空的问题。请注意,代码示例中的路径和URL需要根据实际情况进行修改。