注入和使用Http Angular2

时间:2015-09-23 16:47:50

标签: javascript typescript angular

我有一个服务类,应该调用api并返回结果:

import {Component, View} from 'angular2/angular2';
import { Inject} from 'angular2/di';
import {Http} from 'angular2/http';

var httpMap = new WeakMap<ScheduleService, Http>();
export class ScheduleService {
    meetings: Array<any>;
    http: any;

    constructor(@Inject(Http) http:Http){
        httpMap.set(this, http);
        this.http = http;

        //http.get('/api/sample')
        //   .map(response => response.json())
        //   .subscribe(data => {
        //      this.serverData = data;
        //      });
    }

    getMeetings(){
        var path = '/api/meetings/';
        return httpMap.get(this).get(path);
    }

}

正在调用并正确注入服务类。我遇到的问题是,当我调用getMeetings方法时,它永远不会向/api/meetings发出请求。如果你们在构造函数中注意到get请求/api/sample请求,如果我取消注释并运行程序,我会检查我的network标签,我可以看到请求已经完成。

1 个答案:

答案 0 :(得分:1)

http.get(path)看起来不会发送请求,除非您致电http.get(path).subscribe();,即使您没有对回复做任何事情。

Plunker:https://plnkr.co/edit/b1fxoIUy31EHTC84U344?p=preview

在Plunker中,在控制台中打开网络视图,然后点击 With Subscribe / Without Subscribe 按钮进行比较。

相关问题