What is the best way to transfer an image between Angular components and then showcase it?

I've developed a feature using an observable and I'm attempting to transfer a dataURL from one component to another in order to display it as an image.

Here is the HTML code for the component where I want to send data from:

<canvas id="patternFrame" width="600px" height="600px"></canvas> 
<ion-button color="medium" (click)='sendPattern()'>send</ion-button>

This is the Typescript code for the component where I want to send data from:

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()); // utilizing service to transmit image to color component
  };

Below is the HTML code for the component where I want to send data to:

<img src="" alt="Image" id="onlyImage" width="400" height="200">

And here is the Typescript code for the component where I want to send data to:

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);
            });
  }

Lastly, this is the Typescript code for my service:

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);
  }
}

Answer №1

Please refrain from using

document.getElementById('onlyImage').setAttribute('src',  image);

Instead, it is recommended to assign the image source to a variable. For example:

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
        });
}

In your HTML file, use:

<img [src]="imgSrc" alt="Image" id="onlyImage" width="400" height="200" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to hand off this object to the concatMap mapping function?

I'm currently in the process of developing a custom Angular2 module specifically designed for caching images. Within this module, I am utilizing a provider service that returns Observables of loaded resources - either synchronously if they are already ...

Problem with fetching Grails

I have a table nested within an anchor tag. The table is centered on the page, with each row containing an image. When the page loads, I noticed the following: a) The table initially appears at the top-left corner of the screen. b) As there are multiple v ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

Using jQuery JSONP only functions with URLs from the same site

I am looking to send a request to an API that returns data in json format. The API is located on a sub-domain of the domain where my script will be running (although currently it's on a completely different domain for development, localhost). My unde ...

Ensure that the method is triggered

I have a builder class that implements an interface which it is expected to build. However, I would like to enforce one method of this class to be called at compile time, rather than runtime. The class is designed to be used as a chain of method calls and ...

Converting Ajax to JSON with Jquery offline and Manifest for enhanced offline web applications

Looking to create an offline web application, I'm in the process of transitioning from Ajax to JSON using JQuery offline. Here is the initial Ajax code: $.ajax({ url: contentpage, data: contentpagedata, cache: false }).done(function( html ) { ...

Attempting to insert items into a storage array and subsequently outputting them using a loop

I am attempting to add "contacts" to local storage, and every time I add a new contact I want to refresh it in a jQuery list. I have successfully achieved this without using local storage. However, now I am facing a problem that I can't seem to solve. ...

The process of incorporating a function into a website's source code using a web driver

In the source code, there is a button with an onclick event to change the paragraph content. However, the code provided does not seem to be functioning properly. ((JavascriptExecutor) this) .executeScript("function test123() { y=docume ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

Changing the text color of mat-chips in Angular Material

Having a mat-chip-set and multiple mat-chip elements with a custom product-chip class: <mat-chip-set> <mat-chip class="product-chip" *ngFor="let category of categories"> {{category}} </mat-chip> </mat-chip-s ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

Exploring the Battle of Efficiency: Stateless Components vs. Class Components in the Age of React Hooks - Determining the Superior Approach

Having delved into various online resources and discussions on platforms like Stack Overflow (link here), the consensus seems to lean towards utilizing stateless functions (functional components) whenever possible. Many of the life cycle methods found in ...

Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4? //load the send form if (sendRequest) { sendRequest.open("POST", urlRequest, true); sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlenc ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

Transforming all numbers to a consistent scale with the help of Numeral JS

Is there a way to customize the output of the numeral.js function so that it always returns numbers in thousands? For example, converting 1000000 to 1000k and 100 to 0.1k. console.log( numeral(1000000).format('0a') ); <script src="https ...

Change the color of a c3js chart when it loads

I have been searching for a way to customize the color of a scatter chart's plot, and I came across an example that uses d3 code within the chart http://jsfiddle.net/ot19Lyt8/9/ onmouseover: function (d) { d3.select(d3.selectAll("circle ...