1

I'm working on Angular and I the reduce()operator doesn't return my object. My code is following below:

I've created an interface

interface Example {
  page?: number;
  size?: number;
  name?: string;
}

And I declared a subject to create a data stream and inside of pipe operator, I wanna create a object from the data which I sent through the this.example$.next().

exemple$ = new Subject<Example>();

  get$ = this.exemple$
    .pipe(
      startWith({}),
      reduce(
        (obj, item) => {
          Object.keys(item).forEach(data => (obj[data] = item[data]));
          console.log('obj', obj);
          return obj;
        },
        { page: 15, size: 10 } as Example
      ),
      tap(console.log)
    )
    .subscribe();

  ngOnInit() {
    this.exemple$.next({ name: 'John Paul' });
  }

When the Angular starts up, It send the data and I catch it in console.log() inside of reducer() operator and tap() operator.

I can see the data inside of reduce() but nothing happens inside of tap() . Its like as reduce is not returning the object which I'm returning inside it.

Can anyone help me? Thx

1 Answer 1

1

Your source Observable is exemple$ which is a Subject. The reduce() operator will emit only after the source Observable completes which means you need to call exemple$.complete() (or have some condition that completes the chain).

Maybe you're looking for scan() instead that emits all intermediate results?

Sign up to request clarification or add additional context in comments.

1 Comment

Thx a lot, @martin. Your solution salve me!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.