javascript - 注入和使用 Http Angular2
我有一个服务类,它应该调用一个 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发起请求。如果你们注意到构造函数中有一个对/api/sample的get请求,如果我取消注释它并运行程序,它可以完美工作,我检查network标签时,可以看到请求已经发出。
答案#1
看起来 http.get(path) 不会发送请求,除非你调用 http.get(path).subscribe();,即使你不处理响应。
Plunker: https://plnkr.co/edit/b1fxoIUy31EHTC84U344?p=preview
在 Plunker 中,打开控制台的网络视图,然后点击 With Subscribe/Without Subscribe 按钮进行比较。