[英]How to make ajax call with angular2/http?
我正在使用Angular 2.0.0-beta.0和typescript。 我能夠在沒有任何問題的情況下使用window ['fetch']開啟ajax調用(我不需要使用早期版本中所需的任何變通方法。)
但我無法使用angular2的http進行相同的ajax調用。
這是演示該問題的代碼。 項目文件夾中有三個文件index.html,以及名為app的子文件夾中的boot.ts和app.component.ts。
app.component.ts:
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
providers: [HTTP_PROVIDERS],
template: '<h1>My First Angular 2 App</h1><button (click)="getTasks()">click</button>{{tasks}}'
})
export class AppComponent {
http: Http;
tasks = [];
constructor(http: Http) {
alert(http == null);
this.http = http;
}
getTasks(): void {
this.http.get('http://localhost:3000/tasks/norender');
//.map((res: Response) => res.json())
//it is important to have this subscribe call, since the
//request is only made if there is a subscriber
.subscribe(res => this.tasks = res);
}
}
boot.ts:
import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component'
bootstrap(AppComponent, [HTTP_PROVIDERS]);
index.html的:
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 QuickStart</title>
<!-- 1. Load libraries -->
<script src="https://rawgithub.com/systemjs/systemjs/0.19.6/dist/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/http.dev.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: {emitDecoratorMetadata: true},
packages: {'app': {defaultExtension: 'ts'}}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
您應該添加一個Http提供程序。 您有兩種選擇:
import {HTTP_PROVIDERS} from 'angular2/http';
和:
ng.bootstrap(src.SomeComponent, [HTTP_PROVIDERS]);
在使用該服務的組件上:
從'angular2 / http'導入{HTTP_PROVIDERS};
@零件({
...
提供者:[HTTP_PROVIDERS]
...
})
當我使用舊版本的TypeScript編譯器時,我遇到了類似的問題。 我通過將構造函數參數從http: Http
更改為@Inject(Http) http: Http
來修復它。 當然,您需要導入Inject
才能使用它。
我嘗試在https://code.angularjs.org/tools/system.js上使用SystemJS版本,而不是在rawgithub.com上發布。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.