Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从服务器端资源方法获取图像后,如何将背景图像设置为angular 5中的div标记?_Angular_Typescript - Fatal编程技术网

从服务器端资源方法获取图像后,如何将背景图像设置为angular 5中的div标记?

从服务器端资源方法获取图像后,如何将背景图像设置为angular 5中的div标记?,angular,typescript,Angular,Typescript,嗨,目前我有一个angular 5 GUI和一个spring启动应用程序。我有一个显示图像的角度组件。但是,图像无法显示 avatar.component.html <div class="avatar-circle" [style.background-image]="avatarBgImageStyle" [ngClass]="avatarClasses"> <fa-icon *ngIf="!user?.avatar" icon="user"></fa-ic

嗨,目前我有一个angular 5 GUI和一个spring启动应用程序。我有一个显示图像的角度组件。但是,图像无法显示

avatar.component.html

<div class="avatar-circle" [style.background-image]="avatarBgImageStyle" [ngClass]="avatarClasses">
  <fa-icon *ngIf="!user?.avatar" icon="user"></fa-icon>
</div>
<div class="labels" *ngIf="user && (showFullName || showAccount || showAuthority)">
  <div *ngIf="showFullName" class="full-name">{{ fullName }}</div>
  <div *ngIf="showAccount && user.account" class="secondary-text">{{ user.account.name }}</div>
  <div *ngIf="showAuthority && user.authorities && user.authorities.length" class="secondary-text">{{ 'USER_ROLES.' + authority | translate }}</div>
</div>
在avatar.component.html中,您可以看到我正在设置[style.background image]=“avatarBgImageStyle”,它调用avatar.component.ts中的方法avatarBgImageStyle(),并返回一个字符串(例如,我的spring boot应用程序有一个可以服务于文件请求的资源方法。该资源是安全的

/**
 * REST controller for managing File.
 */
@RestController
@RequestMapping("/api")
public class FileResource {
 @GetMapping("/files/{id}")
    @Timed
    @Secured({AuthoritiesConstants.GLOBAL_ADMIN, AuthoritiesConstants.ACCOUNT_ADMIN, AuthoritiesConstants.CAMPAIGN_MANAGER, AuthoritiesConstants.TEAM_MEMBER})
    public ResponseEntity<Resource> getFile(@PathVariable UUID id) {
        log.debug("REST request to get File : {}", id);

        File file = fileService.findOne(id)
            .orElseThrow(FileNotFoundException::new);

        byte[] bytes = Bytes.getArray(file.getContent());

        ByteArrayResource resource = new ByteArrayResource(bytes);

        return ResponseEntity.ok()
            .contentLength(bytes.length)
            .contentType(MediaType.parseMediaType(file.getType()))
            .body(resource);
    }
}
/**
*用于管理文件的REST控制器。
*/
@RestController
@请求映射(“/api”)
公共类文件资源{
@GetMapping(“/files/{id}”)
@定时
@安全({AuthoritiesConstants.GLOBAL_ADMIN,AuthoritiesConstants.ACCOUNT_ADMIN,AuthoritiesConstants.CAMPAIGN_MANAGER,AuthoritiesConstants.TEAM_MEMBER})
公共响应属性getFile(@PathVariable UUID id){
debug(“获取文件的REST请求:{}”,id);
File=fileService.findOne(id)
.orelsetrow(FileNotFoundException::new);
byte[]bytes=bytes.getArray(file.getContent());
ByteArrayResource资源=新的ByteArrayResource(字节);
返回ResponseEntity.ok()
.contentLength(字节.length)
.contentType(MediaType.parseMediaType(file.getType()))
.机构(资源);
}
}
当我检查开发人员工具时,我可以看到UI正在向服务器发出图像文件请求,但是get请求缺少授权标头。我已经准备好http拦截器来添加身份验证标头。但是,由于背景图像url设置为div标记,它不会将http拦截器调用到attach身份验证令牌,在开发者工具中我可以看到403个禁止的错误

如果我想以字节的形式从服务器访问一个文件并将其设置为div标记的背景图像,你知道我的代码是什么样子的吗

我正在上文件服务课

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

import { FileResponse, AppConfig } from '../models';
import { ConfigService } from './config.service';

@Injectable()
export class FilesService {
  config: AppConfig = this.configService.config;

  constructor(private http: HttpClient, private configService: ConfigService) {}

  get(id: string) {
    return this.http.get<FileResponse>(`${this.config.api}/files/${id}`);
  }

  upload(formData: FormData) {
    return this.http.post<FileResponse>(`${this.config.api}/files`, formData);
  }

  getFileUrl(id: string) {
    return `${this.config.api}/files/${id}`;
  }
}
从'@angular/common/http'导入{HttpClient};
从“@angular/core”导入{Injectable};
从“../models”导入{FileResponse,AppConfig};
从“/config.service”导入{ConfigService};
@可注射()
导出类文件服务{
config:AppConfig=this.configService.config;
构造函数(私有http:HttpClient,私有configService:configService){}
获取(id:string){
返回this.http.get(`${this.config.api}/files/${id}`);
}
上传(formData:formData){
返回this.http.post(`${this.config.api}/files`,formData);
}
getFileUrl(id:字符串){
返回`${this.config.api}/files/${id}`;
}
}
这是我添加json web标记的拦截器

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {
  constructor(private injector: Injector) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (
      request.url.startsWith('/assets') ||
      request.url.startsWith('https://maps.googleapis.com/maps/api/staticmap')
    ) {
      return next.handle(request);
    }

    const authenticationService = this.injector.get(AuthenticationService);
    const notificationService = this.injector.get(NotificationsService);
    const router = this.injector.get(Router);

    if (!!authenticationService.token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${authenticationService.token}`
        }
      });
    }

    return next.handle(request).pipe(
      catchError(err => {
        if (
          request.url !== authenticationService.loginUrl &&
          err instanceof HttpErrorResponse &&
          err.status === 401
        ) {
          authenticationService.logout();
          notificationService.stopInterval();
          router.navigate(['/login'], {
            queryParams: {
              returnUrl: router.url
            }
          });
        }

        return _throw(err);
      })
    );
  }
}
@Injectable()
导出类AuthenticationInterceptor实现HttpInterceptor{
构造函数(专用注入器:注入器){}
拦截(
请求:HttpRequest,
下一步:HttpHandler
):可见{
如果(
request.url.startsWith(“/assets”)||
request.url.startsWith('https://maps.googleapis.com/maps/api/staticmap')
) {
下一步返回。处理(请求);
}
const authenticationService=this.injector.get(authenticationService);
const notificationService=this.injector.get(NotificationsService);
const router=this.injector.get(路由器);
if(!!authenticationService.token){
request=request.clone({
集合标题:{
授权:`Bearer${authenticationService.token}`
}
});
}
返回next.handle(request.pipe)(
catchError(err=>{
如果(
request.url!==authenticationService.loginUrl&&
HttpErrorResponse的错误实例&&
错误状态===401
) {
authenticationService.logout();
notificationService.stopInterval();
router.navigate(['/login']{
查询参数:{
returnUrl:router.url
}
});
}
返回-抛出(错误);
})
);
}
}
谢谢你的帮助 谢谢


<div class="avatar-circle" [ngStyle]="{ 'background-image': avatarBgImageStyle !== 'none' ? avatarBgImageStyle : ''" [ngClass]="avatarClasses">
  <fa-icon *ngIf="!user?.avatar" icon="user"></fa-icon>
</div>

您尝试过这种方法吗?我不完全确定这种方法如何处理异步获取的值,如果设置变量后该值会更新,但我建议您尝试一下这样的方法(遗憾的是,我自己目前无法尝试)。

在您的div中使用这种格式:

[style.background-image]=" 'url(' +avatarBgImageStyle + ')'"

我怀疑它会起作用,因为avatarBgImageStyle()方法返回类似于此url(')的字符串,但是在我使用@Secured({AuthoritiesConstants.GLOBAL_ADMIN,AuthoritiesConstants.ACCOUNT_ADMIN,AuthoritiesConstants.CAMPAIGN_MANAGER,AuthoritiesConstants.TEAM_MEMBER})保护我的资源方法之后它需要一个json web令牌。我能确定的真正问题是我们没有发送json WebToken。对于json WebToken,您应该实现一个
HttpInterceptor
,将令牌附加到发送的每个请求中。是的,我知道。刚才发布了我的interceptor。我认为当您u在div标记中设置背景图像的url。可能需要向我的文件资源发出http请求,并将其作为字节[]获取,并且必须这样做。但不知道代码是什么样子。谢谢。这可能会解析为url(url(23905bd4-730e-11e9-a923-1681be663d3e))所以怀疑它是否有效谢谢。你可以在文件avatar.component.ts.get avatarBgImageStyle()中看到这个函数:string{if(!this.user | | | |!this.user.avatar){return'none'}const url=this.fileservice.getFileUrl(this.user.avatar);return
url(${url})
}。“avatarBgImageStyle”这是一个图像url,然后我的代码将工作。
[style.background-image]=" 'url(' +avatarBgImageStyle + ')'"