How to fire an ajax request in Angular 2?

2020-07-11 06:08发布

问题:

I have 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 like this:

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 while running the application, I can see my Dashboard component gets displayed on the screen. But however from the CourseDetailsService, no http calls are getting fired.

But in the console I could able to see the following printed:

came here in service
done . . . . 

But in my chrome networks tab, I couldn't able to see any request fired to the specified url. Where I am making mistake?

I'm using Angular 2 Alpha 47

回答1:

Basically the part that triggers the request itself it's the 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 */);