Home > database >  data: unknown Object is of type 'unknown'.ts in pipe and map functions in angular
data: unknown Object is of type 'unknown'.ts in pipe and map functions in angular

Time:03-25

I am trying to return some data in pipe and map operators in angular but getting this error: (parameter) data: unknown Object is of type 'unknown'.ts(2571)

I am using angular 12 version.

I was trying to get the data modified as "Round: 0", "Round: 1" etc. instead of 1, 2 etc. on the console

here is my code in the home.component.ts file

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Subscription } from 'rxjs';
import { interval } from 'rxjs';
import { filter } from 'rxjs/operators';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {

  private counterSubsciption!: Subscription;
  constructor() { }

  ngOnInit() {
    // this.counterSubsciption = interval(1000).subscribe(count => {
    //   console.log(count);
    // })

    const firstObservable = new Observable(observer => {
      let count = 0;
      setInterval(() => {
        observer.next(count);
        if(count===2){
          observer.complete();
        }
        if(count>3){
          observer.error("Count is greater than 3!");
        }
        count  ;
      },1000)
    });


    this.counterSubsciption = firstObservable.pipe(filter((data) =>{
      return data > 0;
    }),map((data) => {
      return data;
    })).subscribe((data) => {
      console.log(data);
    }, error => {
      console.log(error);
      alert(error); 
    }, () => {
      console.log('Completed!')
    }
    
    )

  }

  ngOnDestroy() {
    this.counterSubsciption.unsubscribe();
  }

}

CodePudding user response:

Read about Rxjs operators from https://www.learnrxjs.io/learn-rxjs/operators/creation/interval

Instead of wrapping setInterval with new Observable,you can use RxJs interval operator.

 const firstObservable = interval(1000)
      .pipe(
        tap((data) => {
          if (data > 3) {
            throw 'Count is greater than 3!';
          }
        }),
        map((data) => {
          return 'Round'   data;
        })
      );

 firstObservable.subscribe({
   next: (data) => console.log(data),
   error: (err) => console.error(err),
 });
  • Related