Home > Mobile >  Angular RXJS Question - Object is of type 'unknown'
Angular RXJS Question - Object is of type 'unknown'

Time:09-28

I want to run the simple function as below code

    import { Component, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    import { map, filter } from 'rxjs/operators'
     
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })
    
    export class AppComponent implements OnInit {
      objectdata = [];
    
       obs1 = new Observable((observer) => {
        observer.next(1)
        observer.next(2)
        observer.next(3)
        observer.next(4)
        observer.next(5)
        observer.complete()
      }).pipe(
        filter(Data => Data > 2),                    //filter Operator
        map((val) => {return val as number * 2}),    //map operator
      )
       
      ngOnInit() {
        this.obs1.subscribe(
          val => {
            console.log(this.objectdata)
          }
        )
      }
    }

The code filter(Data => Data > 2), , show the error: Object is of type 'unknown', (parameter) Data: unknown, Can I know how to fix it?

CodePudding user response:

When you create an Observable with the constructor, you can just pass the type as a generic.

obs1 = new Observable<number>((observer) {
 // ...
  • Related