How to run ajax request in Angular 2?

I have a service defined in Angular 2 like this:

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 . . .") } } 

and in another component I use this service as follows:

 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(); } } 

and during the launch of the application, I see that my Dashboard component is displayed on the screen. But, however, from CourseDetailsService , no HTTP calls are CourseDetailsService .

But in the console, I was able to see the following:

 came here in service done . . . . 

But on my chrome networks tab, I was not able to see that any request was running at the specified URL. Where am I making a mistake?

I am using Angular 2 Alpha 47

+6
source share
1 answer

Basically, the part that runs the request itself is subscribe , so to make it work, you have to add it.

 // 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 */); 
+7
source

All Articles