1

I found something regarding this, but most examples and explanations are deprecated and it's not applicable to RC1.

import {Injectable} from "@angular/core";
import {Http, HTTP_PROVIDERS, Response, RequestOptions, URLSearchParams} from "@angular/http";
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
constructor( private _http: Http ) {}
GetLoggedUser(){
    return this._http.get('http://dev/api/v1/current-user')
     .map((res:Response) => res.json())
} 
} 

I need to make this call exactly as this legacy code:

$(document).ready(function() {
                    jQuery.ajax({
                        type: 'GET',
                        url: 'http://dev/api/v1/current-user',
                        xhrFields: {
                            withCredentials: true
                        },
                    }).done(function(data) {
                        $('#user').html(JSON.stringify(data));
                    });
                });

So, basically I need to make the call using withCredentials. Any help ?

Marco Jr
  • 6,496
  • 11
  • 47
  • 86

1 Answers1

0

With RC1 you need to extend the BrowserXhr class:

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {}
  build(): any {
    let xhr = super.build();
    xhr.withCredentials = true;
    return <any>(xhr);
  }
}

and override the BrowserXhr provider with the extended:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);

With the upcoming RC2, you'll be able to use a withCredentials attribute in request options.

See these links for more details:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • RC2 ? Is there a RC2 ?? good to know !!! let me try first to use the RC1 way you wrote...BRB – Marco Jr Jun 07 '16 at 14:21
  • Oh, ok ! btw..Thierry, the block containing the "@injectable, export class CustomBrowserXhr" must be on the same service that I wrote my code ? or maybe a new file ? or maybe on my main.ts ? Sorry , I'm feeling difficulty to implement this one. – Marco Jr Jun 07 '16 at 14:26
  • You can put the `CustomBrowserXhr` class into a dedicated file and import it: ` import {CustomBrowserXhr} from './custom.browser.xhr';` – Thierry Templier Jun 07 '16 at 14:46
  • U sure ? (index):25 Error: ReferenceError: BrowserXhr is not defined(…) Take a look on my code at https://jsfiddle.net/marcojr/awp40ero/4/ – Marco Jr Jun 07 '16 at 15:04
  • You don't import the `BrowserXhr` class. I would try this: `import {HTTP_PROVIDERS, BrowserXhr} from '@angular/http';`. – Thierry Templier Jun 07 '16 at 15:05
  • Now I did it...but it's still continue with the same error. Looks like something missing on the system.config.js ?? – Marco Jr Jun 07 '16 at 15:16