How to make Angular 2 send all requests as application / x-www-form-urlencoded

I had a similar problem with Angular 1, so I understand how to implement it, only I miss the last step.

Like last time, the guy who made the backend for our application accepts requests with type application/x-www-form-urlencoded and is exactly the same as Angular 1, so Angular 2 sends them with type application/json .

What I did with ng1 was that in config I changed the http provider to run urlencoded over the body of each request.

In ng2, I see that there is https://angular.io/docs/ts/latest/api/http/BaseRequestOptions-class.html a BaseRequestOptions , which I believe is made specifically for this single documentation, a bit not there , so I'm not sure how to implement this correctly (I'm also new to TypeScript).

How to do this so that each of my post and other requests is sent as urlencoded at the end (I also want the function to run on the body so that it actually points to urlencoded).

In addition: why there is no simpler option for this, since now I see that both ASP.Net and Flask (so, I believe, many others) do not support application\json by default?

EDIT: I created a custom function that I use for every object I submit in the POST module, but I hope there is a simpler and more general solution.

 import { URLSearchParams } from 'angular2/http'; export function urlEncode(obj: Object): string { let urlSearchParams = new URLSearchParams(); for (let key in obj) { urlSearchParams.append(key, obj[key]); } return urlSearchParams.toString(); } 

and then i use it as

 this.http.post('http://localhost:5000/user/auth/login', urlEncode(data)) 
+10
angular typescript
Jan 10 '16 at 11:05
source share
1 answer

Try something like this:

DefaultRequestOptions.ts

 @Injectable() export class DefaultRequestOptions extends BaseRequestOptions{ headers:Headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); } 

boot.ts

 bootstrap(AppComponent,[ HTTP_PROVIDERS, provide( RequestOptions, { useClass: DefaultRequestOptions } ), provide(Http, { useFactory: function(backend, defaultOptions) { return new Http(backend, defaultOptions); }, deps: [XHRBackend, RequestOptions]}) ]); 

IMPORTANT: make sure you have not yet declared HTTP_PROVIDERS in the component where you will use the Http object, or it will override the one you inject into boot.ts.




For another function, you can simply add it to any @Injectable object, add this object to the constructor of your components, and you can call it that way from any component, or you can try to extend the http angular object and override the post method to do this for each post -quest behind the scenes.

+12
Jan 10 '16 at 11:25
source share



All Articles