2017-02-23 94 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); 
     }); 
    }