gpt4 book ai didi

Angular 2 : how to manipulate url query string?

转载 作者:太空狗 更新时间:2023-10-29 17:06:40 25 4
gpt4 key购买 nike

在 Angular 1 中有一个 $location.search() 函数可以操作 URL 查询字符串。什么是 angular2 等价物?

我试过了

import {Location} from 'angular2/angular2';

import {URLSearchParams} from 'angular2/angular2';

没有运气。

最佳答案

简短回答(在 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)
}

文档可以在 Angular2 API Docs for RequestOptions 找到.您会注意到 search 参数是 URLSearchParams 的一种类型

另一个例子在 Angular2 Guides (不要介意 JSONP 的东西,它通常也是如何使用普通 http 请求的查询参数)。

以不同方式解释它的引用:How to utilise URLSearchParams in Angular 2

此外,如果您没有导入 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');
}

}

关于 Angular 2 : how to manipulate url query string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com