tone
tone

Reputation: 1434

How to create an initial Observable<T> in an Angular2 service

I am currently attempting to return an observable from a service in Angular2. If you look at the following code, if I uncomment the line in the constructor, everything works fine, and the consumer of the service won't break. But when I try to remove the call from the constructor, it crashes with: Error: XHR error (404 Not Found) loading http://localhost:3847/rxjs/observable

I believe that it is trying to subscribe to the todo$ property prior to initialisation. So how can I create an initial observer that doesn't actually make the call to the get method straight away? That is, I need some sort of empty Observer that will stop the subscribe line from falling over.

How am I supposed to achieve this?

Tony

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Todo} from './todo';
import {Observable} from 'rxjs/observable'

@Injectable()
export class TodoService {

    public todos$: Observable<Todo[]>;

    constructor(private http: Http) {

        //this.todos$ = this.http.get('api/Todo').map(res => <Array<Todo>>res.json());
    }

    loadData() {
        this.todos$ = this.http.get('api/Todo').map(res => <Array<Todo>>res.json());
    }

}

Upvotes: 0

Views: 229

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657108

import {Observable} from 'rxjs/observable'

should be

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

Upvotes: 2

Related Questions