我有一个页面来显示我的Angular 项目的"啤wine "信息.我在路由快照上收到了啤wine 信息,它正在工作.然后,我获取啤wine 图像的名称并访问API以获取图像.一切都正常,但在html中,所有的域都会出现,只有图像不会.

我在表单上有相同的代码,图像就会出现在那里.我做错了什么?

以下是该组件的代码:

import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  NO_ERRORS_SCHEMA,
  OnInit
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatSidenavModule } from '@angular/material/sidenav';
import { ActivatedRoute } from '@angular/router';
import { MatListModule } from '@angular/material/list';

import { Beer } from '../../model/beer';
import { CommonModule, Location, NgFor, NgIf } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { StartComponent } from '../../shared/components/star-rating/star-rating.component';
import { FileUploadService } from '../../services/file-upload.service';

@Component({
  selector: 'app-beer-view',
  templateUrl: './beer-view.component.html',
  styleUrls: ['./beer-view.component.scss'],
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    NgIf,
    NgFor,
    MatSidenavModule,
    MatButtonModule,
    MatListModule,
    MatCardModule,
    MatToolbarModule,
    MatDividerModule,
    MatIconModule,
    StartComponent,
    CommonModule
  ],
  schemas: [NO_ERRORS_SCHEMA]
})
export class BeerViewComponent implements OnInit {
  beer!: Beer;
  fileName? = '';
  imageShow: any;
  isImageLoading: boolean = true;

  constructor(
    private route: ActivatedRoute,
    private changeDetectorRef: ChangeDetectorRef,
    private location: Location,
    private uploadService: FileUploadService) { }

  ngOnInit() {
    this.beer = this.route.snapshot.data['beer'];
    this.fileName = this.beer.image;
    this.obtainImage();
  }

  onCancel() {
    this.location.back();
  }

  obtainImage(): void {
   console.log("obtain image");
   console.log(this.fileName);
    this.isImageLoading = true;
    this.uploadService.getFile(this.fileName).subscribe(
      (data) => {
        this.createImageFromBlob(data);
        console.log("ok");
        this.isImageLoading = false;
        console.log(this.isImageLoading);
      },
      (error) => {
        console.log("erro");
        this.isImageLoading = false;
        console.log(error);
      }
    );
  }

  createImageFromBlob(image: Blob) {
    let reader = new FileReader();
    reader.addEventListener(
      'load',
      () => {
        this.imageShow = reader.result;
        console.log(this.imageShow);
      },
      false
    );

    if (image) {
      reader.readAsDataURL(image);
    }
  }
}

以下是视图组件的代码:

<mat-card appearance="outlined">

  <mat-toolbar color="primary">
    <h1>Beers Detail</h1>
  </mat-toolbar>

  <mat-table class="mat-elevation-z8">
    <mat-list>
      <mat-list-item><b>NAME : </b>{{ beer.name }}</mat-list-item>
      <mat-divider></mat-divider>
      <mat-list-item><b>TYPE :</b> {{ beer.type }}</mat-list-item>
      <mat-divider></mat-divider>
      <mat-list-item><b>ORIGIN :</b> {{ beer.origin }}</mat-list-item>
      <mat-divider></mat-divider>
      <mat-list-item
        ><b>PRICE :</b>
        {{ beer.price | currency : "EUR" : "symbol" : "1.2-2" }}</mat-list-item
      >
      <mat-divider></mat-divider>
      <mat-list-item><b>RATING :</b> {{ beer.rating }} </mat-list-item>
      <mat-divider></mat-divider>
      <mat-list-item *ngIf="!isImageLoading">
        <img [src]="imageShow" alt="Beer Image">
      </mat-list-item>
      <mat-divider></mat-divider>
    </mat-list>

    <mat-card-actions class="actions-center">
      <button
        mat-raised-button
        (click)="onCancel()"
        class="btn-space"
        type="button" >
        <mat-icon aria-hidden="false" fontIcon="keyboard_arrow_left"></mat-icon>
        Back
      </button>
    </mat-card-actions>
  </mat-table>
</mat-card>

屏幕:

enter image description here

我添加了一些日志(log),我可以看到我已经得到了图像OK:

enter image description here

它正在表单页面上工作:

enter image description here

我已经try 了修复URL,它起作用了.我不知道为什么图像没有出现.

我试着把它放在<mat-card>之外,我删除了所有的东西,除了那行:

<img [src]="imageShow" alt="Beer Image">

我试过:

<img src="{{'data:image/jpg;base64,' + imageShow}}" />
<img src="{{ image_path }}" />

但这并不管用.

谢谢!

推荐答案

由于您使用的是OnPush变化检测,因此需要在分配图像后手动调用变化检测:

this.imageShow = reader.result;
this.changeDetectorRef.markForCheck();

此外,您还应该使用DomSanitizer清理镜像资源

this.imageShow = this.sanitizer.bypassSecurityTrustResourceUrl(reader.result);

Angular相关问答推荐

将Angular Metal的芯片组件集成到我的表单中时出错

在Angular中使用ngFor进行表乘法

Angular 17多内容投影错误

如何将Angular 服务包含在延迟加载的独立组件路由中?

ION标签-从子对象中加载页,保留父对象的S内容

使用 TAB 键时如何聚焦mat-select组件?

Angular 信号 在 effect() 中使用 debounce

Angular 为什么延迟加载返回空路径?

路由链接不在 Ionic 中执行

Cypress 12.8.1 无法使用条纹元素 iframe

在ngOninit方法中直接VS初始化属性

显示 1 个数据而不是所有 ngFor - Angular 11

正确理解 angular14 中的注入 - 必须从注入上下文中调用注入()

Angular 2.0 中 $scope 的替代品

Angular 没有可用于依赖类型的模块工厂:ContextElementDependency

Angular 2 通过 [class.className] 绑定添加多个类

Angular 4 设置下拉菜单中的选定选项

`[(ngModel)]` vs `[(value)]`

为什么用?模板绑定中的运算符?

如何在 Angular 5 react式表单输入中使用管道