Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specification of Observables in TypeScript with Angular2

Tags:

angular

I am trying to create a service that returns an Observable that my components can subscribe to. But I get the following error:

Property 'subscribe' does not exist on type 'Observable'.

I am currently running build alpha.44, and below you will find some code that reproduces the problem.

import {Http} from 'angular2/http';
import {Observable} from 'angular2/core';

export class Backend {
    http: Http;

    constructor(http: Http) {
        this.http = http;
        this.getTeams().subscribe();
    }

    public getTeams(): Observable {
        return this.http.get('/api/teams')
            .map(JSON.parse);
    }
}

Changing the code to return "any" type seems to work, but that removes some of the advantages of using TypeScript. Is there any good way to be able to use strict types for Observables in current builds of Angular2?

like image 562
Etse Avatar asked Oct 25 '15 16:10

Etse


1 Answers

What's returning from http.get is Observable from rxjs, not angular2 Observable. As temporarily solution you can import rxjs Observable from "@reactivex/rxjs/dist/cjs/Observable" (see this plunker).

import Observable from '@reactivex/rxjs/dist/cjs/Observable';

class Backend {
  // ...
  getTeams() : Observable {
    return this.http.get('api/teams.json')
      .map(res => res.json());
  }
}

But IMHO changing the code to return "any" is the best solution at this moment. They do it in angular2 http module for now.

like image 152
alexpods Avatar answered Nov 10 '22 13:11

alexpods