Tips for transforming promise function into rxjs Observables in Angular 10

As a beginner in typescript and angular, I am trying to understand observables. My query is related to a method that fetches the favicon of a given URL. How can I modify this method to use observables instead of promises?

 getFavIcon(url: string): Observable<any> {
      return new Observable((observer) => {
        const hostname = this.getDomain(url);
        const src = 'http://' + hostname + '/favicon.ico';

        const image = new Image();
        image.onerror = () => {
            observer.error({ hasFavourite: false });

        };
        image.onload = () => {
            observer.next({ hasFavourite: true, imageURL: src });
            observer.complete();
        };
        image.src = src;
      });
  }

Answer №1

Observable in TypeScript is similar to a promise, but with the added feature of being a continuous stream that requires complete() for Promise-like behavior

 getFavIcon(url: string): Observable<any> {
      return new Observable((obs) => {
        const hostname = this.getDomain(url);
        const src = 'http://' + hostname + '/favicon.ico';

        const image = new Image();
        image.onerror = () => {
            obs.error({ hasFavourite: false });

        };
        image.onload = () => {
            obs.next({ hasFavourite: true, imageURL: src});
            obs.complete()
        };
        image.src = src;
      });
  }

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

Horizontal Accordion Design for Cascading Style Sheets (CSS) Books

I am currently working on developing a page that features a book layout. This page will include tabs that users can expand individually. If you would like to see a working example, you can check out this link: https://codesandbox.io/s/book-layout-l28gh?fi ...

Experience an enthralling carousel feature powered by the dynamic ContentFlow.js

My website features a cover flow style carousel with 7 images: <!-- ===== FLOW ===== --> <div id="contentFlow" class="ContentFlow"> <!-- should be place before flow so that contained images will be loaded first --> <div class= ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

The issue of Angular UI Bootstrap buttons not updating persists even after the removal of an

My Radio-bottoms are powered by an Array for a Multi-Choice answer setup. <div ng-repeat="option in options"> <div> <button type="button" style="min-width: 100px" class="btn btn-default" ng-model="question.answer" btn-radio="' ...

Struggling to link JSON data with Angular 2 class objects

I am a beginner in Angular 2 and I'm working on creating a service that sends a GET request to receive JSON data. My goal is to bind the results from the JSON to an array of Angular classes. However, I encountered a problem and something seems to have ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

The issue of Angular 12 Bootstrap 5 ngFor accordion remaining open persists

I am currently working on implementing a ngFor dropdown accordion list using Angular 12 and bootstrap 5. However, I am facing an issue where the accordions are staying open and not closing as expected. If anyone has any insights on how to resolve this and ...

How to set a new default environment in Angular CLI for running ng serve

Is there a way to make Angular CLI use a different environment file instead of the default dev when running ng serve? Update I should have clarified my question better. I am aware that we can specify the environment file using the --env switch, but I am ...

In what ways does PROJEN streamline project configuration for infrastructure and application projects?

Exploring PROJEN and AWS CDK has raised questions for me regarding how PROJEN contributes to standardizing project configurations in the context of multiple projects or repositories. While I see its usefulness for a single project or repository through the ...

example of using relative jquery countdown.js

I've been attempting to grasp JavaScript and incorporate the countdown found at this link (specifically, the example with a 300-second countdown), but after spending a few hours on it, I haven't been able to get it functioning properly. I have c ...

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

Issue with Angular Material Auto Complete not selecting items when filtered

Encountered a problem with the mat-autocomplete control in Angular Material where it fails to include the CSS class "mdc-list-item--selected" on the mat-option and also does not add the mat-pseudo-checkbox to a selected option when the contents are display ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Attaching Picture From Array To Vue

Is it possible for me to request assistance? I'm wondering how to bind an image to a vue component or more simply, how do you render an image from an array in vue? Allow me to share my code with you and explain in detail how I have approached this. W ...

How can I store unique and only selected checkbox values in an array using Angular?

I need assistance with creating an array from three checkboxes. The array should only contain the values of the checked checkboxes and should not include duplicates. I have attempted to achieve this functionality, but the values are still being added rega ...

Disable the default marker in Mapbox Geocoder

As a newcomer in the world of ReactJS and Mapbox GL JS, I am working on a project where I have successfully integrated a map with Geocoder, Navigation Controls, and Markers based on locations from a JSON file. However, I encountered an issue - whenever I s ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

When clicking, clear the selected items and avoid the function from repeatedly executing

I am currently facing issues with implementing mat-select-autocomplete in my project. Firstly, I have noticed that the function's (selectionChange)="getSelectedOptions($event)" is triggered every time I click on mat-select-autocomplete. Is there a wa ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

I need help figuring out how to convert a date into Spanish using an Angular pipe in an Ionic 3 application

I need to display a date in Spanish in my Ionic project that I am fetching from SQL Server 2014. Currently, the date is being formatted using an Angular pipe, but it is showing up in English. I have attempted to use I18n for internationalization, but it do ...