即使设置了我的httpheaders

时间:2019-05-27 01:30:20

标签: html angular spring

我有一个使用Spring Boot API从数据库调用的用户列表。

每个用户都具有各种属性,例如用户名,ID,名字,姓氏,注册日期和个人资料照片,这些属性是上传文件的ID(上传后托管在Spring项目主文件夹的子文件夹中)在另一个称为文件的数据库表中。

要获取图像,您必须具有正确的JWT令牌(登录后即可获取)并使用路径:'http://localhost:8082/downloadFile/' + imageid

在上述用户列表下,我创建了一个div,该div将在单击具有所选用户属性的用户之一并显示实际用户个人资料图片后填充。

我找到了一个关于如何将图像链接转换为实际照片的stackoverflow帖子,因此我遵循了the instructions

问题是执行答案中写的内容后,我不断收到此错误:

ERROR Error: 
"Uncaught (in promise): HttpErrorResponse: { 
    "headers": { 
        "normalizedNames:{},
        "lazyUpdate":null 
     },
     "status":403,
     "statusText":"OK",
     "url":"http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292",
     "ok":false,
     "name":"HttpErrorResponse",
     "message":"Http failure response for http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292: 403 OK", 
    "error":{}
}"

这是我的.ts组件:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
  this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
  this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.dataSource.data = u as User[];
  console.log('datasource: ', this.dataSource.filteredData);
  this.users = u;
  console.log('user: ', this.users);
  });
 }

ngOnInit() {
}

onRowClicked(selectedItem) {
  console.log('selected item: ', selectedItem);
  document.getElementById('msg').style.display = 'none';
  document.getElementById('info').style.display = 'block';
  if (selectedItem.photoProfile === 'http://localhost:8082/static.images/user/default.jpg') {
  this.imgSrc = 'C:/Users/Adam/Documents/CODE/Ang/StarAdmin-Free-Angular-Admin-Template/src/assets/default.jpg';
} else if (selectedItem.photoProfile === 'null') {
  console.log('null');
} else {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(currentUser.token);
  this.getFile('http://localhost:8082/downloadFile/' + selectedItem.photoProfile, currentUser.token);
}
}

getFile(url: string, token): any {
const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
this.http.get(url, {
  responseType: 'blob',
})
  .toPromise()
  .then((res: any) => {
    let blob = new Blob([res._body], {
      type: res.headers.get('Content-Type', headers)
    });

    let urlCreator = window.URL;
    this.imgSrc = this.sanitizer.bypassSecurityTrustUrl(
        urlCreator.createObjectURL(blob));
  });
}
}

export interface User {
id: number;
username: string;
firstName: string;
lastName: string;
email: string;
enabled: string;
registeredDate: Date;
}

1 个答案:

答案 0 :(得分:0)

看起来您永远不会传递在GET请求调用上方创建的标头对象。将您的请求更改为:

const headers = new HttpHeaders({'Authorization':'Bearer'+ token});

this.http.get(url,headers = headers,{   responseType:“ blob”, })