5

Specifying Observables in TypeScript with Angular2

 3 years ago
source link: https://www.codesd.com/item/specifying-observables-in-typescript-with-angular2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Specifying Observables in TypeScript with Angular2

advertisements

I am trying to create a service that returns an Obserable 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. Any good way to be able to use strict types for Obseravbles in current builds of Angular2?


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.

Tags angular

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK