我在Angular 2中定义了这样的服务:
import { Inject } from 'angular2/angular2'; import { Http ,Headers , HTTP_PROVIDERS } from 'angular2/http'; export interface CourseInterface { courseId: number, coursePrice: number, authorName: string } export class CourseDetailsService { http: Http; constructor(@Inject(Http) Http) { console.log(Http) this.http = Http; } load() { console.log("came here in service") var headers = new Headers(); headers.append('Authorization',); this.http.get('https://some.api',{ headers : headers }).map(res => console.log("Response came!!!")) console.log("done . . .") } }
在另一个组件中,我使用这样的服务:
import {CourseInterface, CourseDetailsService} from '../services/course'; @Component({ selector: 'dashboard', viewBindings: [CourseDetailsService] }) @View({ template: `Dashboard page laoded
` }) export class Dashboard { constructor(service: CourseDetailsService) { service.load(); } }
在运行应用程序时,我可以看到我的Dashboard
组件显示在屏幕上.但是,从那里CourseDetailsService
,没有http电话被解雇.
但在控制台中,我能够看到以下内容:
came here in service done . . . .
但是在我的chrome networks标签中,我无法看到向指定网址发出的任何请求.我在哪里弄错了?
我正在使用Angular 2 Alpha 47
基本上触发请求的部分本身就是它subscribe
,所以为了使它工作,你必须添加它.
// Service
load() {
var headers = new Headers();
headers.append('Authorization', );
return this.http.get('https://some.api',{
headers : headers
}).map(res => console.log("Response came!!!"))
}
// Component
// 'subscribe' triggers the request!
service.load().subscribe((result) => /* do something with result */);