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.
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');
}
}
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With