2017-02-23 63 views
0

У меня есть служба в угловом 2Угловое 2 подписываются не работает

private todosUrl = "http://localhost:3000/HelloWorld"; // URL to web API 

    constructor (private http: Http) {} 

    public getTodos(): Subscription { 
    this.todoList = []; 
    return this.http.get(this.todosUrl) 
     .map((res: Response) => { 
      if (res.status === 204) { 
       return []; 
      } 
      let todosObj: any = res.json(); 

      return todosObj; 
     }) 
     .flatMap((res: Array<Todo>) => { 
      return res; 
     }) 
     .subscribe((todo: Todo) => { 
      this.todoList.push(todo); 
     }); 
    } 

в http://localhost:3000/HelloWorld возвращает JSON { "Hello World!": "Попробуйте сейчас"}. Но эта функция возвращает ошибку

**Uncaught TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. 
    at Object.subscribeToResult (subscribeToResult.ts:81) 
    at MergeMapSubscriber._innerSub (mergeMap.ts:135) 
    at MergeMapSubscriber._tryNext (mergeMap.ts:131) 
    at MergeMapSubscriber._next (mergeMap.ts:115)** 

любая помощь пожалуйста?

+0

Вы вообще не нуждаетесь в .flatMap, и это вызывает ошибку (поскольку она ожидает получения Observables не res). просто удалите бит .flatMap :) – Cel

ответ

2
private todosUrl = "http://localhost:3000/HelloWorld"; // URL to web API 

    constructor (private http: Http) {} 

    public getTodos(): Subscription { 
    this.todoList = []; 
    return this.http.get(this.todosUrl) 
     .flatMap((res: Response) => { 
      if (res.status === 204) { 
       return null; 
      } 
      return res.json(); 
     }).subscribe((todo: Todo) => { 
      this.todoList.push(todo); 
     }); 
    } 
Смежные вопросы