如何在Angular 2中触发ajax请求? [英] How to fire an ajax request in Angular 2?
问题描述
我在Angular 2中定义了这样的服务:
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();
}
}
,并且在运行应用程序时,我可以看到Dashboard
组件显示在屏幕上.但是,从CourseDetailsService
开始,没有任何HTTP调用被触发.
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 . . . .
但是在我的Chrome网络标签中,我看不到任何触发到指定网址的请求.我在哪里犯错?
But in my chrome networks tab, I couldn't able to see any request fired to the specified url. Where I am making mistake?
我正在使用Angular 2 Alpha 47
I'm using Angular 2 Alpha 47
推荐答案
基本上,触发请求本身的部分是subscribe
,因此要使其正常工作,您必须添加它.
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 */);
这篇关于如何在Angular 2中触发ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!