Observables do not provide any results when used in a pipe with an image src

I recently created a custom pipe for the image src in my application:

It is applied to selectors like this:

<img [src]="myobject?.URL | secure" />

Here's the code snippet for the pipe:

    import { Pipe, PipeTransform } from '@angular/core';
    import { Http, ResponseContentType } from '@angular/http';
    import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/of';

    @Pipe({
      name: 'secure'
    })
    export class SecurePipe implements PipeTransform {

      constructor(private http: Http, private sanitizer: DomSanitizer) { }

      transform(url): Observable<SafeUrl> {

        if (//myboolcondition) {
          return this.http
            .get(url, { responseType: ResponseContentType.Blob })
            .catch(err => Observable.throw(err))
            .map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));
        }
        else {
          // I am facing an issue here where the image doesn't render
// when transitioning to this else block

          return Observable.of(url);

        }
      }
    }

The problem arises when the else part of the condition inside the pipe's code is triggered. It returns an empty response and fails to display the image.

Could you please advise me on how to effectively return the original url specified by "[src]="myobject?.URL" when the else block is executed?

Answer №1

When you return an Observable, it will start emitting values only when you actually subscribe to it. If you wish to directly use observables in your template, you should utilize the AsyncPipe

The AsyncPipe takes an observable or a promise as an argument, subscribes to it or attaches a then handler, and then holds off until the asynchronous result is received before passing it to the caller.

Updated code snippet

<img [src]="myobject?.URL | secure | async" />

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

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

Troubleshooting: Vue.js file upload encountering OPTIONS 404 error

In my express app, I have configured CORS and most of the routes are working fine. However, I'm facing an issue with a specific component used for uploading images: <input type="file" class="form-control" @change="imageChanged"> <div @clic ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this: <div *ngIf="groupCheck; els ...

Unlocking Column Data Tooltips in Angular Datatables: A Step-by-Step Guide

I have a single datatable and was wondering how to implement tooltips for when hovering over table cells. I tried the following code snippet, which successfully populated the tooltips. However, I am interested in achieving the same functionality using Angu ...

Tips for connecting Vue data to a dropdown menu

While diving into Vue.js, I'm encountering a puzzling issue. Despite receiving data from the server (5 records), it's not populating the <select> element properly. Instead of multiple options, all I see is a single one displaying {{dept.DNa ...

Having issues fetching data from the store with the latest version of Ngrx

I've been trying to integrate ngrx into my Angular project, but I'm facing a challenge with retrieving and displaying data. Despite various attempts based on online resources, I can't seem to fetch the data from the store even though the sta ...

Creating a back button for returning to the previous page

I have created an Angular application that retrieves data from an API. However, I am facing an issue where the data is lost when navigating to another route and then returning to the table route. Is there a way to switch routes without losing the data? &l ...

Next.js encountering page not found error due to broken link URL

Currently, I am working on implementing a login system in next.js. In the login page, I have included a Link to the Register page using the Link href attribute. However, every time I click on that link, it displays a message saying "404 page not found." Al ...

The text is not appearing properly in an HTML file due to issues with

Hi trying to display the text received from the controller's scope. Here's what I have attempted: HTML: <div ng-repeat="item in sResults"></div> Controller JavaScript: $scope.sResults = []; function App( ){ var Label ...

Transfer the data in the columns of Sheet1 to Sheet2 and eliminate any duplicates using Google App Script

Is there a way to transfer only unique rows from a SOURCE Spreadsheet to a DESTINATION spreadsheet? Spreadsheet #1 (SOURCE) - This sheet contains ID's and Names, but has duplicate rows. There are over 500k rows in this sheet and it is view-only. Spre ...

Not receiving connections on localhost port 3000

Our team has successfully created a basic Express Node website https://i.stack.imgur.com/5fwmC.png We attempted to run the app using DEBUG=express_example:* npm start https://i.stack.imgur.com/NI5lR.png We also tried running it with node DEBUG=express_ ...

After incorporating some movement effects into my menu, suddenly none of the buttons were responding

While working on my website and trying to add a close menu button, I encountered an issue where all the menu buttons stopped functioning. Here is the HTML code snippet: <div id="openMenuButton"> <span style= "font-size:30px;cu ...

An error has occurred: Cannot locate a difference supporting the object '[object Object]' of type 'object'. The NgFor only enables binding to Iterables like Arrays

I've already checked for similar questions, but none of them provided a solution that worked for me. I'm facing an issue when receiving an object with the following structure: { "_embedded": { "students": [ { ...

Utilizing Components for Efficient Development in Angular

I have three different types of objects: A - FirstName - LastName B - FirstName - LastName - MiddleName C - FirstName My goal is to create a component that can be used to easily create these objects using a simple form where I can input the necessa ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

What is the procedure for verifying the type of an element using chai?

Is there a way to determine if an element is either an "a" tag or a "div" tag? I've tried the following code, but it's not working as expected: it('has no link if required', () => { const wrapper = shallow(<AssetOverlay a ...

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

Creating a JSON object from an array of data using TypeScript

This might not be the most popular question, but I'm asking for educational purposes... Here is my current setup: data = {COLUMN1: "DATA1", COLUMN2: "DATA2", COLUMN3: "DATA3", ..., COLUMNn: "DATAn"}; keyColumns = ["COLUMN2", "COLUMN5", "COLUMN9"]; ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...