在角度1中,有一个$location.search()
可以操纵URL查询字符串的函数.angular2等价物是多少?
我试过了
import {Location} from 'angular2/angular2';
Run Code Online (Sandbox Code Playgroud)
和
import {URLSearchParams} from 'angular2/angular2';
Run Code Online (Sandbox Code Playgroud)
没有运气.
Eri*_*son 13
简答(在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)
}
Run Code Online (Sandbox Code Playgroud)
文档可以在Angular2 API Docs for RequestOptions中找到.你会注意到search
param是一种类型URLSearchParams
另一个例子是Angular2指南(不介意JSONP的东西,它通常是如何使用查询参数的普通http请求).
参考以不同的方式解释它: 如何在Angular 2中使用URLSearchParams
此外,如果您没有在您的可观察功能中导入RxJSapp.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');
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21899 次 |
最近记录: |