简体   繁体   English

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

[英]Angular2: how to manipulate url query string?

in angular 1 there is a $location.search() function which can manipulate URL query string. 在angular 1中有一个$location.search()函数,它可以操作URL查询字符串。 What is the angular2 equivalent? angular2等价物是多少?

I tried 我试过了

import {Location} from 'angular2/angular2';

and

import {URLSearchParams} from 'angular2/angular2';

with no luck. 没有运气。

Short Answer (in TypeScript): 简答(在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)
  }

The docs can be found at Angular2 API Docs for RequestOptions . 文档可以在Angular2 API Docs for RequestOptions中找到 You will notice that the search param is a type of URLSearchParams 您会注意到search参数是一种URLSearchParams

Another example is in the Angular2 Guides (don't mind the JSONP stuff, it's generally how to use query parameters for normal http requests too). 另一个例子是Angular2指南 (不介意JSONP的东西,它通常是如何使用查询参数的普通http请求)。

Reference to explain it a different way: How to utilise URLSearchParams in Angular 2 参考以不同的方式解释它: 如何在Angular 2中使用URLSearchParams

Also, if you didn't import RxJS in your app.ts observable functionality will break. 此外,如果您未在app.ts导入RxJSapp.ts观察的功能将中断。

More Complete Example in TypeScript: 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');
    }

}

Below worked for me. 以下为我工作。

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

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

Do you use typescript ? 你用打字稿吗? If so, you might need to reference the d.ts file containing the typings for angular2 with the following code : 如果是这样,您可能需要使用以下代码引用包含angular2类型的d.ts文件:

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

I did a little project where I had this problem, webstorm wouldn't find anything from angular2, and highlight my imports as errors. 我做了一个小项目,我遇到了这个问题,webstorm找不到angular2的任何内容,并突出显示我的导入为错误。 Including this line of code before importing from angular2 solved it. 在从angular2导入之前包括这行代码解决了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM