2016-04-29 63 views
3

我正在使用Angular 2.0.0-beta.16并尝试从我的RESTful API中获取数据。我有以下服务:Angular2 Http/Jsonp无法提出请求

import {Injectable}  from 'angular2/core'; 
import {Jsonp, Response, Headers, RequestOptions} from 'angular2/http'; 
import {Store}   from './store'; 
import {Observable}  from 'rxjs/Observable'; 
import 'rxjs/Rx'; 

@Injectable() 
export class StoreService { 
    constructor(private jsonp: Jsonp) { 

    } 

    getStores(): Observable<Store[]> { 
     console.log("getting stores"); 
     // let headers = new Headers({ 'Content-Type': 'application/json' }); 
     // let options = new RequestOptions({ headers: headers }); 
     return this.jsonp.get("http://localhost:8080/stores") 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
     console.log(res.status); 
     if (res.status < 200 || res.status >= 300) { 
      throw new Error('Bad response status: ' + res.status); 
     } 
     let body = res.json(); 
     return body.data || {}; 
    } 


    private handleError(error: any) { 
     // In a real world app, we might send the error to remote logging infrastructure 
     let errMsg = error.message || 'Server error'; 
     console.error(errMsg); // log to console instead 
     return Observable.throw(errMsg); 
    } 
} 

从我的分量,我打电话getStores()。我知道它正在进入getStores()函数,因为我得到了console.log消息。但是,没有其他事情发生。没有任何要求可以在chrome开发工具中看到。没有错误记录到控制台。根本不值一提。我已经尝试JsonpHttp,但他们都给出了相同的结果。

回答

5

您需要订阅由getStores()返回的observable。观察对象是懒惰的,如果没有subscribe()或`toPromise()

getStores().subscribe(val => { console.log(val); }; 
+0

就是这样!谢谢。你介意链接到这个特定块上的一些文档吗? – Gregg

+0

我发现这很有趣[https://gist.github.com/staltz/868e7e9bc2a7b8c1f754] – Picci

+0

http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2 .html您的链接似乎已中断。 –