在角度1中有一个$location.search()
函数可以操作URL查询字符串。 angular2等价物是什么?
我试过
import {Location} from 'angular2/angular2';
和
import {URLSearchParams} from 'angular2/angular2';
没有运气。
答案 0 :(得分: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)
}
可以在Angular2 API Docs for RequestOptions找到文档。您会注意到search
参数是URLSearchParams
另一个例子是Angular2 Guides(不要介意JSONP的内容,它通常也是如何将查询参数用于普通的http请求)。
参考以不同的方式解释:How to utilise URLSearchParams in Angular 2
此外,如果您未在app.ts
可观察功能中导入RxJS,则会中断。
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');
}
}
答案 1 :(得分:2)
以下为我工作。
@Component({
selector: 'start'
})
@View({
template: `<h1>{{name}}</h1>`
})
export class Start {
name: string;
constructor(routeParams: RouteParams){
this.name = 'Start' + routeParams.get('x');
}
}
答案 2 :(得分:1)
/// <reference path="typings/angular2/angular2.d.ts" />
我做了一个小项目,我遇到了这个问题,webstorm找不到angular2的任何内容,并突出显示我的导入为错误。在从angular2导入之前包括这行代码解决了它。