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