Incorporating observables into an existing axios post request

Currently, I have an API using axios to send HTTP POST requests. These requests contain logs that are stored in a file. The entire log is sent at once when a user signs into the system.

Now, I've been instructed to modify the code by incorporating RxJS and sending the file contents (logs) in streams every x minutes...

If you have any idea on how to tackle this issue or know of any helpful resources, your input would be greatly appreciated!

async deliverData(UserName: string, Log: string[]): Promise<UserInfo>{
  return this.apiService.post({
    baseUrl: Something.SomethingUrl,
    endpoint: "/post/log"
    timeout: 15000
    headers:{      }
   },
    {
      userName: userName,
      Log: Log[0]
     }

Answer №1

Consider using axios-observable instead of axios for managing subscriptions. Using subscriptions over promises allows for easier unsubscription, which is a big advantage. To implement this, you can place your log sending request subscription within a BehaviorSubject (import { BehaviorSubject } from 'rxjs';) and schedule the call to the behavior subject on a timer. Here's an example:

export default class PollValue<T> {
    date: Date;
    value: T;

    constructor(value: T) {
        this.date = new Date();
        this.value = value;
    }

    // Ensures a minimum amount of time has elapsed
    getTimeout(minTimeMS: number) {
        const timeElapsed = new Date().getTime() - this.date.getTime();
        return timeElapsed < minTimeMS ? minTimeMS - timeElapsed : 0;
    }
}

// using true or false to indicate whether we sent logs the last time or not
const sendLogs = new BehaviorSubject(new PollValue<boolean>(false));
sendLogs.subscribe(lastValue => {
    setTimeout(() => {
        if (thereAreLogsToSend) {
            // sendLogs is a function containing your axios-observable instance and request 
            this.yourLogService.sendLogs(<pass logs here>).subscribe(result => {
                sendLogs.next(new PollValue(true));
            });
        } else {
            sendLogs.next(new PollValue(false));
        }
         
    }, lastValue.getTimeout(900000)); // ensure at least 15 mins have elapsed before sending again

    if (someStopSendingCondition) {
        sendLogs.unsubscribe();
    }
});

If you're looking to send your request as a stream, you may find examples here helpful. I don't have much experience working with streams in REST architecture, so I may not be the best resource for that specific topic.

I hope this information proves useful, even though my response may be delayed...

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

A class definition showcasing an abstract class with a restricted constructor access

Within my codebase, there is a simple function that checks if an object is an instance of a specific class. The function takes both the object and the class as arguments. To better illustrate the issue, here is a simplified example without delving into th ...

Utilizing TypeScript to export a class constructor as a named function

Imagine you have this custom class: export class PerformActionClass<TEntity> { constructor(entity: TEntity) { } } You can use it in your code like this: new PerformActionClass<Person>(myPersonObject); However, you may want a more co ...

Tips for properly executing directives in sequential order while using async in Angular 13

I created a standard registration form using Angular and implemented an async directive (UserExistsDirective) to validate if the email is already taken. To manage error messages, I also utilized a second directive (ValidityStyleDirective) which is also use ...

Managing arrays in local storage with Angular 2+

I seem to be missing a crucial element in my endeavor to save and retrieve an array in local storage within my Angular 4 application. The array is fetched from the server and stored in a variable named 'aToDo' with type 'any', like so: ...

What is the best way to bring in the angular/http module?

Currently, I am creating an application in Visual Studio with the help of gulp and node. Node organizes all dependencies into a folder named node_modules. During the build process, gulp transfers these dependencies to a directory called libs within wwwroo ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Using an External JavaScript Library in TypeScript and Angular 4: A Comprehensive Guide

My current project involves implementing Google Login and Jquery in Typescript. I have ensured that the necessary files are included in the project: jquery.min and the import of Google using <script defer src="https://apis.google.com/js/platform.js"> ...

Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker ...

The specified argument, 'void', cannot be assigned to a parameter that expects 'SetStateAction | undefined'

Currently, I am engaged in a TypeScript project where I am fetching data from an endpoint. The issue arises when I attempt to assign the retrieved data to my state variable nft using the useState hook's setNft function. An error is being thrown specif ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Invoke a specific URL during an HTML5 upload

So I've got this code that allows for file upload via drag and drop using HTML5 in the browser. $(function(){ var dropbox = $('#dropbox'), message = $('.message', dropbox); dropbox.filedrop({ // Customizing upload settin ...

Is there a way to selectively filter and display certain data in an Angular data table?

I am currently working on a project using Angular 7 frameworks that involves dealing with large amounts of data. One of the tasks is to filter out trial units based on the 'userName' field in the raw data. I have various usernames such as user22 ...

Having trouble managing TypeScript in conjunction with React and Redux

As a newcomer to TypeScript, I find myself struggling to grasp the concepts and know where to start or stop. While there are abundant resources available online, I have not been able to effectively utilize them in my project. I am hopeful for some guidance ...

Display the concealed mat-option once all other options have been filtered out

My current task involves dynamically creating multiple <mat-select> elements based on the number of "tag types" retrieved from the backend. These <mat-select> elements are then filled with tag data. Users have the ability to add new "tag types, ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Axios sends back HTML content in response for Laravel and VUE integration

Within my api.php file, I have implemented two routes: Route::get('resume-list/{templateID}', 'BasicController@getAllResumes'); Route::get('resume/single/{id}', 'BasicController@getResume'); The first route is fun ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

Navigating with Angular: Transmitting dynamic URL parameters to components

I currently have the following routes defined: const routes: Routes = [ { path: ':product/new', children: [{ path: 'std/:country', component: SignUpComponent, data: { ...

A step-by-step guide on updating a deprecated typings package manually

Currently, I am developing a NodeJS application using TypeScript and incorporating numerous Node packages. However, not all of these packages come with TypeScript definitions, so Typings is utilized to obtain separate definition files. During the deployme ...