Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds.

Currently, I have a function that returns a Promise, but I need it to return the outcome of that Promise:

public static getWifiInfos(): Observable<Promise<ConnectionInfo>> {
    return Observable
        .interval(3000)
        .map(() => Hotspot.getConnectionInfo());
}

Any suggestions on how to achieve this desired functionality?

Answer №1

To solve your problem, you should utilize the switchMap function, which links an interval to the results of a different Observable. It's difficult to explain it in any other way.

public static fetchWirelessDetails(): Observable<ConnectionInfo> {
  return <Observable<ConnectionInfo>> Observable
    .interval(3000)
    .switchMap(() => 
      Observable.fromPromise(Wifi.getConnectionInfo())
    )
}

Answer №2

Here is a suggestion for you to try:

private connectionInfoSubject = new Subject<ConnectionInfo>();

connectionInfoObservable = this.connectionInfoSubject.asObservable();

public static getWifiInfos(): Observable<ConnectionInfo>{
    Observable
        .interval(3000)
        .map(() => {
            // Assuming Hotspot.getConnectionInfo is a synchronous call                
            this.connectionInfoSubject.next(Hotspot.getConnectionInfo());
            // If Hotspot.getConnectionInfo returns a promise
            Hotspot.getConnectionInfo().then(result => {
                this.connectionInfoSubject.next(result);
            })
        });
}

I hope this information proves helpful!

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

Creating a typescript object shape without an index signature involves specifying the exact properties

I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface: interface Params { [key: string]: string | number | boolean | undefined | null; } This interface specifies that the k ...

Encountering the "DevToolsActivePort file does not exist" error when executing Angular e2e tests via GitHub Actions

Currently delving into the world of GitHub actions, I am in the process of executing Angular e2e tests within a continuous integration workflow. Utilizing the basic project structure generated by the Angular CLI, I have primarily focused on adjusting the ...

Merging JSON Array of Objects from Separate Http Services in Angular 8

I am currently working on a new Angular 8 project where I need to retrieve JSON data from two different services in my component. Both sets of data are arrays of objects. My goal is to merge the objects from these arrays and then post the combined data bac ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

Having to reinstall node modules is a repetitive task that must be done after each build of an Angular

Formulating this question has been quite challenging for me. I really hope it is clear. Despite my extensive searches, both on this platform and beyond, I have not been able to find any reference to the behavior I am experiencing. For the past few ...

Setting up Angular 7 to interact with a .Net Core Web API in Visual Studio 2017

I have been on a quest to find the solution to my programming dilemma. The issue at hand involves a Visual Studio 2017 (Community) project that contains an Angular 7 app with a .NET Core web API backend all within the same project. I have successfully test ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

What is the method for obtaining the properties of a type as an array in Typescript?

In the given scenario: class Foo { constructor( private one: string, private two: string, private three: string) { } } Is there a way to create an array containing the type's properties? For example, I need to gene ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

Angular2 Animation for basic hover effect, no need for any state change

Can anyone assist me with ng2 animate? I am looking to create a simple hover effect based on the code snippet below: @Component({ selector: 'category', template : require('./category.component.html'), styleUrls: ['./ca ...

Uncovering a commitment to reveal the valuable information within

Whenever my Spring Boot back-end responds to front-end requests, it structures the data like this: { "timestamp":[2022,6,16], "status":"OK", "data": { "products": [{"product ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...

When the down arrow key is pressed, the focus of the radio button is lost

I've been facing a persistent accessibility issue with the main-component in Angular. This component contains four different templates, but depending on the radio button selection, other templates are displayed. The problem arises when these templates ...

Activating the microphone device on the MediaStream results in an echo of one's own voice

I am in the process of creating an Angular application that enables two users to have a video call using the Openvidu calling solution. As part of this application, I have implemented a feature that allows users to switch between different cameras or micr ...

Next.js Custom App now offers full support for Typescript in Accelerated Mobile Pages (

I am looking to implement AMP in my custom Next.js project using Typescript. While the official Next.js documentation does not offer support for Typescript, it suggests creating a file called amp.d.ts as a workaround. My application includes a src folder ...

Tips for successfully sending an array of numbers using TypeScript and React

Exploring Types in React is new to me and I'm still navigating my way through it. My current challenge involves adding numbers from a form within a child component to an existing array of numbers. To tackle this, I've initialized a useState hoo ...

What is the best way to end a Google OAuth session using Firebase on an Ionic 2 application?

My Ionic 2 app integrates Google Authentication using Firebase. I have implemented a logout button within the app that calls the Firebase unauth() method. However, this only disconnects the Firebase reference and does not terminate the Google OAuth session ...

Typescript's async function failing to execute properly

I'm currently facing an issue with my code and I'm a bit puzzled as to where the problem lies. The console is displaying the correct data for this.allNominations, but it appears that the third for-loop is not being executed at all. As a result, t ...

When working with TypeScript, encountering an error involving an array containing an index signature

When attempting to change an object's type to a generic array using the as keyword, I encountered an error. interface TestType { action: TestGeneric<number>[] } type TestGeneric<T> = { [key: string]: T } const func = () => { ...