midnightnoir
midnightnoir

Reputation: 731

Can't get basic Observables to work

I've been learning Angular, and so far I've got the basic foundations down. I want to dive deeper into RxJS and Observables but every time I try to follow tutorials online, there is always these trivials errors, I feel so stupid that I can't solve them, and get stuck on the first step of these tutorials. For example, I'm following Rangle.io's tutorial on Observables, but .next(42) .next(43), and .push(value) returns error saying Argument of type '42' is not assignable to paramter of type 'number[]'.

In some tutorials and RxJS official GitHub, they use import Rx from 'rxjs/Rx' or import * Rx from 'rxjs'Rx, but it doesn't work in my project. Can't figure out why I have to use import { Observable } from 'rxjs/Observable' instead of importing everything.

Anyway, what am I missing that is causing the error in the operator?

import { Component } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import 'rxjs/observable/from';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  private data: Observable<Array<number>>;
  private values: Array<number> = [];
  private anyErrors: boolean;
  private finished: boolean;

  constructor() {}

  init() {
    this.data = new Observable(observer => {
      setTimeout(() => {
        observer.next(42);
      }, 1000);

      setTimeout(() => {
        observer.next(43);
      }, 1000);

      setTimeout(() => {
        observer.complete();
      }, 3000);
    });

    const subscription = this.data.subscribe(
      value => this.values.push(value),
      error => this.anyErrors = true,
      () => this.finished = true
    );
  }
}

Upvotes: 1

Views: 512

Answers (2)

Steve Land
Steve Land

Reputation: 4862

The error you're seeing is because you're declaring that your Observable will produce elements of type Array<number> but then you're setting it to produce number values.

If you change

private data: Observable<Array<number>>;

to

private data: Observable<number>;

that should resolve your issue.

Remember that Observables should be set to the type of each object that they will emit e.g. <number>, rather than a list or collection of emissions like <Array<number>> *

*Unless of course your observable does actually emit a collection of objects every time...

Upvotes: 4

DeborahK
DeborahK

Reputation: 60518

There is a working Plunker here: http://plnkr.co/edit/SA25mG?p=preview

It only has two imports:

import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';

You don't show the HTML, so I assume you have something similar to this plunker?

Upvotes: 0

Related Questions