Having trouble grasping this concept in Typescript? Simply use `{onNext}` to call `this._subscribe` method

After reading an article about observables, I came across some code that puzzled me.

I am struggling to comprehend the following lines ->

return this._subscribe({
                onNext: onNext,
                onError: onError || (() => {}),
                onCompleted: onCompleted || (() => {})
            });

1) This syntax is new to me, can someone explain what it does exactly?

When using typeof, it indicates that it's an object, but it seems like an object within a function, which seems odd to me.

2) Since I couldn't grasp the code, I experimented and found that if I return

return {
                onNext: onNext,
                onError: onError || (() => {}),
                onCompleted: onCompleted || (() => {})
            }

The code fails to reach Point Two (refer to -> // PointTwo below, after "return new Observable((obs)")

I believe the answer to the second question might be linked to the first one.

export class Observable<T> {
    /** Internal implementation detail */
    private _subscribe: any;

    /**
      * @constructor
      * @param {Function} subscribe is the function that is called when the 
      * observable is subscribed to. This function is given a subscriber/observer
      * which provides the three methods on the Observer interface:
      * onNext, onError, and onCompleted
    */
    constructor(subscribe: any) {
        if (subscribe) {
            this._subscribe = subscribe;
        };

    }


    // public api for registering an observer
    subscribe(onNext: any, onError?: any, onCompleted?: any) {
        if (typeof onNext === 'function') {
            return this._subscribe({
                onNext: onNext,
                onError: onError || (() => {}),
                onCompleted: onCompleted || (() => {})
            });
        } else {
          throw new Error("Please provide a function")
        }
    }

    static of(...args): Observable {
        return new Observable((obs) => {

       //pointTwo

            args.forEach(val => {
              console.log("3") 
              obs.onNext(val)
              });
            obs.onCompleted();

            return {
                unsubscribe: () => {
                    // just make sure none of the original subscriber's methods are never called.
                    obs = {
                        onNext: () => {},
                        onError: () => {},
                        onCompleted: () => {}
                    };
                }
            };
        });
    }
 }


 Observable.of(42).subscribe((num) => {console.log("number is -> " + num)})

Answer №1

This example does not pertain specifically to TypeScript. It simply showcases defining an object literal within a function invocation rather than before calling the function:

const myFunction = (obj) => {
    console.log(obj);
};

const objVariable = { key1: 'value1', key2: 2 };

// passing in an object stored in a variable
myFunction(objVariable);

// defining an object literal directly during the function call
myFunction({ key1: 'value1', key2: 2 });

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

When attempting to debug JavaScript in Edge with Visual Studio Code, an error message stating 'Failed to load source map for chrome-error...' was encountered

Attempting to troubleshoot JavaScript code in Visual Studio Code is resulting in an error: Could not read source map for chrome-error://chromewebdata/: Unexpected 503 response from chrome-error://chromewebdata/edge-elixir-neterror.rollup.js.map: Unsupporte ...

Navigating Angular's Credit Card Input Functionality

I am looking to limit the input capacity to 16 numbers and add a space between each set of 4 numbers. After conducting an extensive search for a credit card input that allows users to enter 16 digits with a " - " or space in between, all results were for ...

The size of the popup does not align properly with the content within it

After creating an extension for Chrome, I specified the dimensions of the popup to be 600 x 300 px. Everything was working perfectly until Chrome updated to version 27. As shown in the screenshot, I set the width and height using CSS, but there is still a ...

Having trouble printing a section of a webpage after making CSS adjustments

When trying to print part of a page, I used the following method. It successfully prints that portion of the page, however, it does not preserve the CSS effects. <body> <h1><b><center>This is a test page for printing</center&g ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

Error message indicating that the event "OnkeyDown" is not in sync within the React application

Hey everyone! I'm a beginner in web development and I'm struggling to understand why the event "OnKeyDown" is triggered the second time. My task involves changing (increasing, decreasing) parts of a date (day, month, year, hour, minutes, seconds) ...

Guide to setting up sub-routes in fastify

Currently, I am incorporating fastify as the web framework for my nodejs project. My aim is to organize and call all routes from a specific directory while having a base route established in the main JS file, similar to how it's done in express. Despi ...

JavaScript event listener on the "change" event only triggers when changed manually [CodePen]

Check out this jsFiddle I created with all the data and information related to the issue. It should make it easier to understand what's happening: Take a look here: http://jsfiddle.net/lukinhasb/GuZq2/ $("#estado").val(unescape(resultadoCEP["uf"])); ...

What is the best way to programmatically define the value for the MaterialUI grid size property using TypeScript?

Is there a way to dynamically pass a value to the Grid size props like XL in TypeScript? For instance, *Update for further clarification import Grid, { GridSize } from "@material-ui/core/Grid"; let value: GridSize = 12/4; xl={value} Error: Type &apos ...

Modifying properties within child components

Within my parent Vue Page, I have inserted a FormInput component inside my form. new.vue <b-form @submit.prevent="submit"> <FormInput :name="name"/> <b-button @click="submit">Save</b-button> <b-form> <script> i ...

Encountering an issue of duplicate key error when using multiple v-for loops with various keys

I've encountered an issue while working on a Python application that utilizes Vue.js. A ticket came my way with an error message stating: [Vue warn]: Duplicate keys detected: ''. This may cause an update error. (found in Root) The pro ...

Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation? Below is the code snippet that has be ...

Issue with Vuex: currentUser state not persisting after page refresh

I'm currently working on a Vue.js SPA that utilizes Rails 6 API as the backend and Vue-cli (legacy webpack template). After signing in a user, everything seems to be functioning correctly. I can view the user details, it updates my setCurrentUser mut ...

Is there a way to store a file in a server directory using the <a href='mypdf.pdf'> tag?

I find myself in a bit of a bind. I have a document that needs to be saved in my server directory, which is attached in an <a href='mypdf.pdf'>My pdf</a> tag. The issue is that the filename, mypdf.pdf, is dynamically changing via Jav ...

Issue with useEffect causing a delay in updating the state value

I'm facing an issue with a component that displays the number of people who have liked a book. The problem is, I can't seem to consistently get the correct result in my states. Here's the code snippet: ///Fetching the book details cons ...

Managing the challenges of handling numerous AJAX post errors stemming from multiple form submissions

I am currently developing a PHP application that will be used to present multiple choice questions as well as text-based questions. The functionality I have implemented involves using Javascript code to submit user responses via ajax to the PHP server. He ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

Guide to using Ajax to load a partial in Ruby on Rails

Whenever a search is triggered, I have a partial that needs to be loaded. This partial can take a significant amount of time to load, so I would prefer it to be loaded via Ajax after the page has fully loaded to avoid potential timeouts. Currently, my app ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...