0

In my code, I'm trying to map through an array of strings using observables and I want to see that value inside of an input. I printed my code on the console and I can see the array but I could not assign this to an input field. I also get the error Type 'Subscription' is missing the following properties from type 'Observable<any[]>': source, operator, lift, subscribe, and 3 more. I want to see the array element inside it but what I see is {{ slider$ | async }}. What should I do to fix my code?

HTML:

<input type="input" value="{{ slider$ | async }}" />

TS:

const slides = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4'];
let slider$: Observable<any[]>;
slider$ = of(slides).pipe(map((response) => {return response;})).subscribe(console.log);
2
  • Can you be more clear what you’re looking for. The source of slider$ is an array. Do you want to see four inputs, or the first of the array etc. Commented Nov 1, 2022 at 19:15
  • I want to see the first element of the array @AndrewAllen Commented Nov 1, 2022 at 19:33

1 Answer 1

2

Stackblitz

import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map, tap } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  template: `
    <input type="input" value="{{ slider$ | async }}" />
  `,
})
export class AppComponent {
  slides: string[] = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4'];

  slider$: Observable<string> = of(this.slides).pipe(
    tap(console.log), // ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4']
    map((arr: string[]) => {
      return arr[0]; // map to 1st element of the array
    }),
    tap(console.log) // 'Slide 1'
  );
}

When you do this {{ slider$ | async }} the async pipe is subscribing (and cleaning up subscription on component destroy) to the observable slider$. In your code you are subscribing directly so that slider$ becomes a Subscription rather than the expected Observable, hence the error. If you wish to debug part way through the stream you can use the tap pipeable operator. This is also used for side effects.

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

Comments

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.