Angular2:如何操作 url 查询字符串?

Angular2: how to manipulate url query string?

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

我试过了

import {Location} from 'angular2/angular2';

import {URLSearchParams} from 'angular2/angular2';

运气不好。

你使用打字稿吗?如果是这样,您可能需要使用以下代码引用包含 angular2 类型的 d.ts 文件:

/// <reference path="typings/angular2/angular2.d.ts" />

我做了一个遇到这个问题的小项目,webstorm 无法从 angular2 中找到任何东西,并将我的导入突出显示为错误。在从 angular2 导入之前包括这行代码解决了它。

下面对我有用。

@Component({
  selector: 'start'
})
@View({
  template: `<h1>{{name}}</h1>`
})
export class Start {
  name: string;

    constructor(routeParams: RouteParams){
        this.name = 'Start' + routeParams.get('x');
    }
}

简答(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. You will notice that the search param is a type of URLSearchParams

找到文档

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

参考以不同的方式解释它:

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

}