【问题标题】:Angular2 Http / Jsonp Not Making RequestAngular2 Http / Jsonp 未发出请求
【发布时间】:2016-04-29 19:06:42
【问题描述】:

我正在使用 Angular 2.0.0-beta.16 并尝试从我的 RESTful API 获取数据。我有以下服务:

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 我都试过了,但它们都给出了相同的结果。

【问题讨论】:

    标签: rest angular angular2-services


    【解决方案1】:

    你需要订阅getStores()返回的observable。 Observables 是懒惰的,没有subscribe() 或 `toPromise()

    什么都不做
    getStores().subscribe(val => { console.log(val); };
    

    【讨论】:

    猜你喜欢
    • 2013-10-20
    • 2017-03-12
    • 2012-08-26
    • 2013-11-23
    • 2016-07-23
    • 2015-11-12
    • 2012-03-25
    • 2016-06-10
    相关资源
    最近更新 更多