简短回答(TypeScript):
// Import you were looking for
import {Http, Response, Headers, RequestOptions, URLSearchParams} from 'angular2/http';
//... jump down some code
export class MyRegistrationsComponent {
constructor(private http: Http) { }
getDudesAndDudettes() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
// Have to make a URLSearchParams with a query string
search: new URLSearchParams('firstName=John&lastName=Smith}')
});
return this.http.get('http://localhost:3000/MyEventsAPI', options)
.map(res => <Dudes[]>res.json().data)
}
这些文档可以在以下位置找到:RequestOptions 的 Angular2 API 文档 https://angular.io/docs/ts/latest/api/http/index/RequestOptions-class.html。您会注意到search
参数是一种类型URLSearchParams https://angular.io/docs/js/latest/api/http/URLSearchParams-class.html
另一个例子是在Angular2 指南 https://angular.io/docs/ts/latest/guide/server-communication.html#!#search-parameters(不要介意 JSONP 的东西,它通常也是如何对正常的 http 请求使用查询参数)。
参考以不同的方式解释它:如何在 Angular 2 中使用 URLSearchParams https://stackoverflow.com/questions/34386367/how-to-utilise-urlsearchparams-in-angular-2/34413223#34413223
另外,如果你没有导入RxJS https://angular.io/docs/ts/latest/guide/server-communication.html#!#rxjs在你的app.ts
可观察到的功能将会被破坏。
TypeScript 中更完整的示例:
import {Component} from 'angular2/core';
import {Http, Response, Headers, RequestOptions, URLSearchParams} from 'angular2/http';
import {Registrant} from './registrant';
import {Registration} from './registration';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'my-registrations',
templateUrl: 'app/my-registrations.component.html',
inputs: ['registrant']
})
export class MyRegistrationsComponent {
constructor(private http: Http) { }
private _registrantionsUrl: string = 'http://localhost:3000/MyEventsAPI';
private _title = 'My Registrations Search';
public registrant: Registrant = { firstName: "John", lastName: "Smith" };
findMyEvents() {
let body = JSON.stringify(this.registrant);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
search: new URLSearchParams(`firstName=${this.registrant.firstName}&lastName=${this.registrant.lastName}`)
});
return this.http.get(this._registrantionsUrl, options)
.toPromise()
.then(res => <Registration[]>res.json().data)
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}