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

Navigating HTML with Node.js and Express.js

I have been working on routing multiple HTML pages in my project. The index.html file loads without any issues, but when I try to load raw.html, an error message pops up: Error: Failed to lookup view "error" in views directory Below is part of my app.j ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

Combining a JSON object with a dropdown menu within an Ionic 3 Angular 4 application

I've hit a roadblock while attempting to integrate a JSON response into an ion-option tag in my HTML code: <ion-item> <ion-label>Country</ion-label> <ion-select formControlName="country"> ...

Generating a Random Number Within a Specified Range

function generateRandomNumberBetween(start, stop) { var low = Math.ceil(low); var high = Math.floor(high); return Math.floor(Math.random() * (high - low + 1)) + min; } function testRandomNumberGeneration() { var start = parseInt(prompt("Enter low ...

The error message that appeared states: "TypeError Object[object object] does not have the SubSelf method, TypeError Object[object object] does not

As I delved into a WebGL project, leveraging the powerful Sim.js and Three.js libraries, an unexpected obstacle emerged: At a certain point, within the code, the constructor for THREE.Ray is utilized in this manner: var ray = new THREE.Ray( this.camera.p ...

Should I use YUICompressor or a comparable tool in PHP?

After using yuicompressor.jar for quick JavaScript minimisation on my test server, I ran into issues when deploying to my public server due to server restrictions on java execution. This means I need to find an alternative solution for on-the-fly JS compre ...

What is the best way to incorporate Drift bot JS code into a static React NextJs application, such as a landing page?

I'm a beginner with ReactJS and I recently created a static website using ReactJS & NextJs. I decided to integrate a chatbot called 'Drift', but when following the installation instructions to insert JavaScript code in the <head> of HT ...

Utilizing navigation buttons to move between tabs - material-ui (version 0.18.7)

I'm currently using material ui tabs and attempting to incorporate back and next buttons for tab navigation. However, I've run into an issue - when I click the back or next buttons, the tabs do not switch. Here is my existing code snippet: ... ...

I encountered an issue while attempting to install dependencies listed in the package.json file using the npm install command

npm encountered an error with code 1 while trying to install a package at path C:\Users\HP\Desktop\workings\alx-files_manager\node_modules\sharp. The installation command failed due to issues with the sharp plugin and its ...

Clear function of signature pad not working inside Bootstrap modal dialogue box

Currently, I'm working on implementing a signature pad dialogue box using Bootstrap modal. When the user clicks on the "Complete Activity" button, a dialog box should pop up with options for yes or no. If the user selects yes, another dialog box shoul ...

How to align an unordered list horizontally in HTML without knowing the number of items

I'm currently developing a web page that needs to display an unknown number of items using the ul/li HTML tag. Here are my requirements: The list should utilize as much horizontal space as possible The list must be horizontally centered, even if lin ...

Display Image based on AngularJS value

Within my data, there exists a value {{catadata2.EndorsementList['0'].Rating}}. This value can be either 3, 4, or 5. Based on this value, I am looking to display the image <img src="/assets/img/rating.png" /> a certain number of times. For ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

Alert: Attempting to access an undefined value in an indexed type

I would like to find a way in Typescript to create a hashmap with indexable types that includes a warning when the value could potentially be undefined during a lookup. Is there a solution for this issue? interface HashMap { [index: number]: string; } ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

What is causing the #reset button to trigger the Flow.reset() function when the #gameboard does not contain any child elements?

Whenever I click on the resetBtn, it triggers the Flow.reset function regardless of whether the gameboard has child elements. Am I using the hasChildNodes() method incorrectly? const resetBtn = document.querySelector('#reset'); resetBtn.addEventL ...

Adding elements to a global array via a callback function in JavaScript: A step-by-step guide

I am currently working on querying and adding users to a global array from my database. My goal is to store the elements in this global array so that I can access it from any part of my application. app.get("/admin/orders", (req, res) => { Q ...

Is it possible to import Vue directly from the "/path/to/vue.js" file without using npm or NodeJs?

Is it possible to build a web app using just a single index.js file and importing other available files like shown in this image: https://i.stack.imgur.com/02aFF.png encountering the error message: import not found: default Do you have to use Vuejs wit ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Utilizing Angular to call a function defined in Renderer2 and assign it to a

In my directive, I have configured a table value to be replaced by an anchor tag using the renderer.setProperty method. The anchor tag is enhanced with a "click" attribute that I am unsure how to interact with: either through accessing the function "onCli ...