Javascript 如何在 Angular 2 中触发 ajax 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34104221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:56:02  来源:igfitidea点击:

How to fire an ajax request in Angular 2?

javascriptangular

提问by Ant's

I have service defined in Angular 2 like this:

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

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 Dashboardcomponent gets displayed on the screen. But however from the CourseDetailsService, no http calls are getting fired.

在运行应用程序时,我可以看到我的Dashboard组件显示在屏幕上。但是,从CourseDetailsService,没有 http 调用被触发。

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?

但是在我的 chrome 网络选项卡中,我看不到对指定 url 发出的任何请求。我哪里出错了?

I'm using Angular 2 Alpha 47

我正在使用 Angular 2 Alpha 47

回答by Eric Martinez

Basically the part that triggers the request itself it's the subscribe, so to make it work you have to add it.

基本上触发请求本身的部分是subscribe,因此要使其工作,您必须添加它。

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