我创建了一个带有 obervable 的服务,我尝试将 dataURL 从一个组件发送到另一个组件,然后将其显示为图像。
我想从中发送数据的组件的 html
<canvas id="patternFrame" width="600px" height="600px"></canvas>
<ion-button color="medium" (click)='sendPattern()'>send</ion-button>
我要从中发送数据的组件的打字稿
import {StageColorService} from '../../services/stage-color.service';
constructor(private stageColorService: StageColorService){}
ngOnInit(){}
sendPattern(){
const canv =document.getElementById('patternFrame') as HTMLCanvasElement;
this.stageColorService.sendStage(canv.toDataURL()); // use service to send image to color component
};
我要将数据发送到的组件的 html 代码
<img src="" alt="Image" id="onlyImage" width="400" height="200">
我要向其发送数据的组件的打字稿代码
import {StageColorService} from '../../services/stage-color.service';
constructor(private stageColorService: StageColorService) { }
ngOnInit() {
this.stageColorService.stage$
.subscribe(
image => {
console.log('image subscription'+ image);
document.getElementById('onlyImage').setAttribute('src', image);
});
}
我的服务的打字稿代码
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StageColorService {
private stageSource = new Subject<any>();
stage$ = this.stageSource.asObservable();
constructor() { }
sendStage(st: any){
this.stageSource.next(st);
}
}
请避免这种情况 document.getElementById('onlyImage').setAttribute('src', image);
而是使用一个变量来显示。例如:
import {StageColorService} from '../../services/stage-color.service';
public imgSrc:string;
constructor(private stageColorService: StageColorService) { }
ngOnInit() {
this.stageColorService.stage$
.subscribe(
image => {
console.log('image subscription'+ image);
this.imgSrc = image
});
}
并在 html 中使用
<img [src]="imgSrc" alt="Image" id="onlyImage" width="400" height="200" />
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句