vbilici
vbilici

Reputation: 152

Angular2: how to manipulate url query string?

in angular 1 there is a $location.search() function which can manipulate URL query string. What is the angular2 equivalent?

I tried

import {Location} from 'angular2/angular2';

and

import {URLSearchParams} from 'angular2/angular2';

with no luck.

Upvotes: 10

Views: 22417

Answers (3)

Eric D. Johnson
Eric D. Johnson

Reputation: 11737

Short Answer (in 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. You will notice that the search param is a type of 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).

Reference to explain it a different way: How to utilise URLSearchParams in Angular 2

Also, if you didn't import RxJS in your app.ts observable functionality will break.

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

}

Upvotes: 13

Badal Singh
Badal Singh

Reputation: 918

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');
    }
}

Upvotes: 2

Arnaud Boeglin
Arnaud Boeglin

Reputation: 773

Do you use typescript ? If so, you might need to reference the d.ts file containing the typings for angular2 with the following code :

/// <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. Including this line of code before importing from angular2 solved it.

Upvotes: 1

Related Questions