Home > Net >  Mapping an Array of Strings and Assigning Them to an Input
Mapping an Array of Strings and Assigning Them to an Input

Time:11-02

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);

CodePudding user response:

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.

  • Related