Srikanth Reddy
Srikanth Reddy

Reputation: 545

unable to subscribe the observable in angular

I'm newbie to rxjs. I had read the document of angular and tried the rxjs basic concept in ts file. Unfortunately it's throwing me an error. My code is as like follows :

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Rxtest';
  squareOdd = of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 !== 0),
    map(n => n * n)
  );
  squareOdd.subscribe(x => console.log(x));

}

The error I'm facing after compile is as like below : ERROR in src/app/app.component.ts(17,3): error TS2300: Duplicate identifier 'squareOdd'. src/app/app.component.ts(17,3): error TS2717: Subsequent property declarations must have the same type. Property 'squareOdd' must be of type 'Observable', but here has type 'any'. src/app/app.component.ts(17,40): error TS2304: Cannot find name 'x'.

Upvotes: 1

Views: 226

Answers (1)

Supradeep
Supradeep

Reputation: 3266

Move your logic into a method like ngOnInit, constructor method or any custom method based on your requirement. Add the logic in any of the class prototype methods or in the constructor method. For example in your case :

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Rxtest';
  squareOdd = of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 !== 0),
    map(n => n * n)
  );

  ngOnInit() {
    this.squareOdd.subscribe(x => console.log(x));
  }

}

Here, instance member squareOdd is defined and the subscription is created on init.

Read about ngOnInit here

To understand more about Javascript classes, read Here

Upvotes: 3

Related Questions