简体   繁体   中英

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());
    }

}
import {Observable} from 'rxjs/observable'

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM