Issue With RXJS Subject Wrapper

Discussão em 'Angular' iniciado por Venfi Oranai, Outubro 22, 2024.

  1. Venfi Oranai

    Venfi Oranai Guest

    I have a class that contains an RXJS Subject and I'd like to add a shorthand on the class to allow for either piping or subscribing without needing to access the subject directly, but I'm having some issues with making it work.

    This is the basic version of my class (the full code is more complex, but this allows for minimal reproduction):

    class Wrapper:
    private subject = new Subject<string>();


    I've tried two solutions, neither of which have worked. For the sake of the example I'll only reference the pipe, but the same issue also occurs when trying to wrap the subscribe.

    The first is with a getter that simply returns a reference to the subject's pipe.

    public get pipe() {
    return this.subject.pipe;
    }


    However, when I do this I get the following error TypeError: Unable to lift unknown Observable type once I add any operators (for example, new Wrapper().pipe(tap(console.log))).

    My second attempt included calling the subject's pipe inside the function in order to replicate the original's behavior, like so:

    public pipe(...operators: OperatorFunction<any, any>[]) {
    return this.subject.pipe(...operators);
    }


    When attempting this I get the following compilation error A spread argument must either have a tuple type or be passed to a rest parameter. I have managed to find a workaround by casting the operators parameter like so this.subject.pipe(...(operators as [])), but I imagine there's got to be a better way.

    If anybody knows of a way to achieve what I'm aiming for it would be greatly appreciated. I'd prefer a solution based on my first method if possible, but if that's impossible then an alternative to the workaround I have in the second method would also be great.

    Thanks in advance and have a lovely rest of your week

    Continue reading...

Compartilhe esta Página