Adding a baseURI to the image src in Angular 5 is causing issues with dynamically loading images

I am currently working on Angular 5.2.1 and I am facing an issue with loading an image from a server using its source URL.

Here is the HTML code:

<img #image [src]="cover" class="img-fluid" alt="NO image">

And here is the TypeScript code in image-loader.component.ts file:

import { Component, OnInit, Input, AfterViewInit,ViewChild,ElementRef} from '@angular/core';
    import { EventAccessService } from '../../../event/services/event-acces.service';

    @Component({
      selector: 'loader',
      templateUrl: './loader.component.html',
      styleUrls: ['./loader.component.scss']
    })
    export class EventCardComponent implements OnInit, AfterViewInit {
      @Input('cover') cover: any;

    @ViewChild("image", {read: ElementRef}) image: ElementRef;

      constructor(private service: EventAccessService) {

      }
    ngOnInit() {}
     ngAfterViewInit() {

        console.log(this.image.nativeElement.currentSrc);
        this.image.nativeElement.src=this.cover
        console.log(this.image.nativeElement.src);
    }
}

When checking Chrome console, it shows the following result:

The base URI http://localhost:4200/(which is concatenated to the variable cover (which contains the full link to the image), causing the image not to load properly.

If anyone can provide assistance or guidance on how to resolve this issue, it would be greatly appreciated!

EDIT:

Even after directly assigning cover to image.nativeElement.src within ngAfterViewInit, the issue still persists.

Answer №1

In my example, I utilized RxJS by incorporating the image URL from the server into a BehaviorSubject as shown below.

.html

<img [src]="photoHandlerService?.userProfilePhotoChanged$ | async" #userProfilePhoto>

.ts

 @ViewChild('userProfilePhoto') userProfilePhoto: ElementRef;

 constructor(public photoHandlerService: PhotoHandlerService) { }

  ngAfterViewInit(): void {
    console.log(this.userProfilePhoto.nativeElement.src);
  }

service.ts

 private profilePhoto: string = 'assets/images/jpgs/profilePhoto.jpg';
 private userProfilePhotoSubject$: BehaviorSubject<string> = new BehaviorSubject<string>(this.profilePhoto);
 userProfilePhotoChanged$: Observable<string> = this.userProfilePhotoSubject$.asObservable();

 constructor()

setUserProfilePhoto(photoUrl: string): void {
    this.userProfilePhotoSubject$.next(photoUrl);
}

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

Filtering in RxJS pipelines can be compared to an if-else statement

I'm not very familiar with JS and RxJS, so please pardon me if my question seems trivial. Here is a code snippet that I didn't write: prepare(): Observable<any> { const i = of({}).pipe( // Check if file type is image fil ...

Activate the input event for a text box when the ng model is assigned from a different angular method

Is it feasible to activate the input event of a text box when a value is assigned to ng-model from another function? <p><input type="text" [(ngModel)]="testValue" (input)="modelupdated(testValue)"/></p> <p><button type="button ...

Is there a way to automatically close the previous accordion when scrolling to a new one on the page?

Currently, I am working with the material-ui accordion component and facing an issue where all accordions are initially opened. As I scroll down the page and reach a new accordion, I want the previous ones to automatically close. The problem arises when tr ...

Preloading Images with Custom URLs for a Fancy Image Display

I am working on creating a gallery page where the images are displayed in a fancyBox. In order to optimize loading times, I am using a PHP script to resize the original large image files on the server side and output smaller, lighter versions for the fancy ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

Once the submit button is clicked in Angular Dev Extreme, validation processes are triggered once more

Currently experiencing an issue on a page with textboxes and validations. After entering values into the textboxes and clicking submit, the values successfully pass to the database, but the validations continue to appear again upon submitting. This problem ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

The route information is not appearing on the screen

I am facing an issue with my application's route called home. The content on this route is not being displayed; instead, only the menu from app.component is shown. I believe I might be overlooking something obvious. Can someone assist me with this pro ...

Unlock the Power of RxJS Observables in Angular

Issue: My goal is to navigate to the login page if firebase-auth does not have a user logged in, and to an alternate page if a user is already logged in. To achieve this, I plan to call a function within a constructor service. private checkLoginStatus() ...

The problem of I18n localization/merging not functioning properly in Angular 10 post-upgrade from Angular 7

Angular CLI: 10.2.0 Node: 12.14.1 OS: win32 x64 \\Angular: 10.1.6 \\... common, compiler, compiler-cli, core, forms \\... language-service, localize, platform-browser \\... platform-browser-dynamic, r ...

How can you verify the value of a disabled HTML input element in TestCafe using Typescript?

TestCafe Typescript - how to verify the value of a disabled HTML input element? Despite being disabled for user interaction, I want to ensure that this element still holds the anticipated value. example public async checksomething(text: string) { co ...

Error message stating: rxjs and firebase encountered a TypeError when attempting to add property 0 because the object is not

My angular application interacts with firebase firestore as the backend database. I am working on a function to retrieve document snapshots from firestore in a generic way. Here is the code snippet where I encounter an error: /** * Get a 'liste ...

What causes different errors to occur in TypeScript even when the codes look alike?

type Convert<T> = { [P in keyof T]: T[P] extends string ? number : T[P] } function customTest<T, R extends Convert<T>>(target: T): R { return target as any } interface Foo { x: number y: (_: any) => void } const foo: Foo = c ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Setting the height of CKEditor 5: A comprehensive guide

How can I adjust the height of the CKeditor angular component? The documentation suggests we can set the editor style to: min-height: 500px !important; However, this solution does not seem to be effective for me. Any other suggestions? ...

What is the best way to apply styling exclusively to a child component?

I am currently working on a coding project that involves a parent component and multiple child components. My main goal is to adjust the position of a filter icon by moving it down 5 pixels on one specific child component. The issue I am facing is that no ...

The process of adding new files to an event's index

I'm trying to attach a file to an event like this: event.target.files[0]=newFile; The error I'm getting is "Failed to set an indexed property on 'FileList': Index property setter is not supported." Is there an alternative solution fo ...

Is it possible for member variables to be reinitialized when clicking on a Component? Are there any alternative methods to prevent this from happening

How can I prevent the productList array in the CartComponent from being reinitialized when clicking on the cart tab after adding items to it through addItem function? export class CartComponent implements OnInit { public productList: any[] = []; ...

The React Quill interface is unable to load due to an undefined window

I recently integrated React Quill into my Next.js project and everything was functioning properly. However, I encountered an issue when attempting to incorporate ImageResize into the editor. Upon adding the line Quill.register('modules/imageResize&ap ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...