Is it possible to pass an external function to the RxJs subscribe function?

Upon examining the RxJS subscribe method, I noticed that:

    subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;

So, I decided to create an example initialization function like this:

  private initialize(): void{
this.dataBaseService.fetchPersons().subscribe(
   (persons: Person[]) => {
    this.behaviorSubject.next(persons);
    this.subject.next(persons);
  },
  error => console.error(error),
  () => console.log('Complete!')
);

}

In Typescript, is it necessary to provide a lambda function as an argument? Can I create a function elsewhere and then use it as an argument?

For instance, consider this function:

       (persons: Person[]) => {
    this.behaviorSubject.next(persons);
    this.subject.next(persons);
  }

Create it in a higher class and subsequently pass it as an argument.

I attempted to define a method within a class:

  someFunction( persons: Person[] ){
this.behaviorSubject.next(persons);
this.subject.next(persons);

}

and tried to pass it to the init function

    private initialize2(): void {
  this.dataBaseService.fetchPersons().subscribe(
    this.someFunction(),
    error => void,
    () => console.log('Complete!');
  )
}

However, I encountered an error:

An argument for 'persons' was not provided.

What type of argument do I need to provide if it's the initialization of this parent method?

Answer №1

Make sure to pass your function without including the parentheses (), as this will cause it to be called immediately:

someFunction( people: Person[]) {
    this.behaviorSubject.next(people);
    this.subject.next(people);
}
    
private initialize(): void {
    this.dataBaseService.retrievePersons().subscribe(
        this.someFunction, // <- pass it without ()
        error => void,
        () => console.log('Process complete!')
    )
}
    

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 tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

The challenges of $location.search().name and base href in application URLs

I am working on an Angular app and my URL appears as http://localhost:8080/personal?name=xyz. To extract the 'xyz' value in JavaScript, I am using $location.search().name. Here is a snippet of my code: app.js app.config(function ($locationProv ...

An error is thrown when using AngularJS .length property

Currently, I am carrying out a regular task within my Filter to verify if angular.module('someApp') .filter('filterSomeData',['$filter',function ($filter) { return function (items, keyObj) { var filterObj ...

Having trouble retrieving data from a remote URL with angucomplete-alt

Utilizing the angucomplete-alt directive for creating an autocomplete list through a get request. Successfully fetching results from the Github API: <div angucomplete-alt id="ex5" placeholder="Search projects" pause="500" selected-object="selectedProj ...

Issue with Angular JS orderBy when sorting by numerical fields is not functioning as expected

Within my controller, I implemented code to convert the rank into a Float data type. details.rank = ''; $scope.order = function (predicate) { $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; if (predicate == & ...

How can the size of the font in a <div> be adjusted based on the number of characters present?

I am attempting to create a basic HTML and CSS layout with two div blocks, each 1000px wide, within a parent container that is 3000px wide. <div class="blocks"> <div class="block-a">text 1</div> <div class="block-b">text 2& ...

Learning how to serve static files in a virtual directory with Angular Universal and Asp Net Core

I am currently working on an Angular Universal + Asp Net Core App. One of my tasks involves serving a static file from a "virtual directory". In the ASP NET Core code, I have implemented the following: app.UseFileServer(new FileServerOptions { ...

Employing condition-based require() statements in JavaScript

I am currently experimenting with conditionally loading modules that are Vue components. Review the code snippet below for a better understanding: index.js My goal is to dynamically load different components based on the window URL (since I cannot use vu ...

Using jQuery to iterate through JSON data obtained from a web service

In this code snippet, I am attempting to retrieve a JSON response from a PHP page and then iterate through it to display the name field of each JSON object. However, for some reason, nothing is being alerted out. <html> <head> <title>A ...

Is there a way to execute Javascript in Django without revealing static files?

When setting up payments on my Django site using Stripe, I realized that the .js file is visible under Sources in the developer tools when inspecting elements on any browser. This presents a potential security risk as anyone can access this file. How can ...

While observing a camera in motion, the particles tinted by texture display sporadic flickering on WebGL and Three.js

Check out this jsfiddle I created to illustrate an issue with particles "flickering" when colored using a texture and the camera is moving. Update: The problem occurs even when there is no animation or movement on the particles. If you notice flickering o ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

Refreshing a page using AJAX form functionalities

After spending some time searching, I am unable to find a satisfactory solution to my issue. I have a "finance" tracker that includes hidden divs which are displayed using jQuery when the corresponding button is clicked. Additionally, I have an Asset Track ...

Issue Loading Angular 2: Preflight Response Invalid (redirect) Error

Utilizing Angular 2 alongside a Laravel PHP Framework for my API, the Angular 2 project runs on http://localhost:4200/, while the Laravel PHP Framework operates on http://localhost:80/laravel/public. Upon executing the following code snippet within my Ang ...

Is it necessary to incorporate the OnInit function in Angular 8+ components if I have no intention of modifying it?

I've been working on a project using Angular 8. One thing I've noticed is that when I use the command line to generate components, they are automatically created with OnInit included. For example: export class SideDrawerComponent implements On ...

Breaking up and processing a given string in JavaScript: Splitting and token

When it comes to dealing with this specific JavaScript requirement, the challenge lies in working with a string such as: “ [ condition12 (BRAND) IN 'Beats by Dr. Dre & D\’Silva of type Band’ of type 'IDENTIFIER_STRING’ ] ...

Exporting a named export for every HTTP method is the way to go with NextJs

I'm currently working on a project to create an Airbnb clone using NextJs. The tutorial I'm following is using an experimental version, while I've opted for the latest version of NextJs. One aspect that's been causing confusion for me i ...

Tips for sending a structured search query to the findOne() function in MongoDB with Node.js

I have a Restful service built with node.js that takes user input to create a query string for MongoDB. However, whenever I try to pass this query to findone() in MongoDb and call the service, it displays a "query selector must be an object" message in the ...

Utilizing Express.js: Passing the req Object to Middleware without the Need for a New Multer Route

Hello to the Express.js and StackOverflow communities! I hope this question is not a duplicate, as I searched and found nothing similar. Currently, I am working on a project using Multer with Express to enable users to upload images, which will be saved a ...

Implementing the sticky positioning property to keep a div container fixed at the bottom of the page

As Bootstrap 4 no longer supports .affix, I had to look for an alternative solution to keep a box fixed. I needed a div container to remain fixed as you scroll to it. My current workaround is using: .fixedcard{ position: sticky; top:75%; } However, th ...