有没有像JQuery for Angular2这样的$.param()函数?
我知道Angular 1特别有类似的服务,Angular1 Equivalent
我检查了Angular 2网站here,他们有一个POST的演示,但他们在请求的正文中发送了一个JSON。
我当前的,不工作的,尝试
saveEdits() {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
this._http.post("ajax/update-thingy", JSON.stringify(this.dataJson), options)
.map(this.extractData)
.toPromise()
.catch(this.handleError);
// update in Angular 1 using JQuery function
// $http({
// method : 'POST',
// url : 'ajax/update-thingy',
// data : $.param($scope.formData),
// headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// });
}
extractData(res: Response) {
let body = res.json();
if (body === 'failed') {
body = [];
}
return body || [];
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Promise.reject(errMsg);
}
或者如果在我的Angular2中更容易获得JQuery,也许这是一种方法。
UPDATE
我确实解决了自己的问题。请看我的答案below!
我解决了自己的问题。
这是我做的,我使用了Angular 2的URLSearchParams。它运作得很好。一点都不复杂,易于使用。
import { Headers, RequestOptions, Http, URLSearchParams } from '@angular/http';
saveEdits() {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let params: URLSearchParams = this.serialize(this.myObj);
this._http.post("ajax/update-thingy", params, options)
.map(this.extractData)
.toPromise()
.catch(this.handleError);
this.selectedBill = null;
}
serialize(obj: any) {
let params: URLSearchParams = new URLSearchParams();
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var element = obj[key];
params.set(key, element);
}
}
return params;
}
有一个内置的序列化功能,但它没有导出..所以我们需要一些解决方法..
你可以这样做:https://plnkr.co/edit/ffoaMVbwSOIX5YNLo2ip?p=preview
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { DefaultUrlSerializer, UrlSegment, UrlTree } from '@angular/router';
@Component({
selector: 'my-app',
template: `
<div>
<h2>{{way1}}</h2>
<h2>{{way2}}</h2>
</div>
`,
})
export class App {
private way1: string;
private way2: string;
constructor() {
let myParams = {you: 'params', will: 'be', here: '!!'};
// way 1
let serializer = new DefaultUrlSerializer();
let nackedUrlTree = serializer.parse('');
nackedUrlTree.queryParams = myParams;
this.way1 = 'way1: ' + serializer.serialize(nackedUrlTree);
// way 2
let urlSeg = new UrlSegment('', myParams);
this.way2 = 'way2: ' + urlSeg;
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}