确认后端API是否正确返回了Authorization头信息,若未返回则需修改API代码,添加Authorization头信息。
在Angular中配置请求拦截器,在每个HTTP请求中添加Authorization头信息。示例代码如下:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authToken = this.authService.getAuthorizationToken();
const authReq = req.clone({ setHeaders: { Authorization: authToken } });
return next.handle(authReq);
}
}
@NgModule({
declarations: [...],
imports: [...],
providers: [
AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
其中,getAuthorizationToken()方法为获取本地存储中的Authorization Token。
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class ApiService {
private apiUrl = 'http://example.com/api/';
constructor(private http: HttpClient) { }
getData() {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
})
};
return this.http.get(this.apiUrl + 'data', httpOptions);
}
}
其中,'Bearer '为Authorization类型,localStorage.getItem('auth_token')获取本地存储中的Authorization Token。