我在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',<my username password>); 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: ` <h1>Dashboard page laoded</h1> ` }) export class Dashboard { constructor(service: CourseDetailsService) { service.load(); } }
在运行应用程序时,我可以看到我的仪表板组件显示在屏幕上.但是,从CourseDetailsService,没有激活http调用.
但在控制台中,我能够看到以下内容:
came here in service done . . . .
但是在我的chrome networks标签中,我无法看到向指定网址发出的任何请求.我在哪里弄错了?
我正在使用Angular 2 Alpha 47
解决方法
基本上触发请求的部分本身就是订阅,因此要使其工作,您必须添加它.
// Service load() { var headers = new Headers(); headers.append('Authorization',<my username password>); 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 */);