How do I write an Angular 2 service with CORS in Ionic?

I'm having trouble moving my Angular 1 JavaScript service to a Angular 2 TypeScript service using http to make a CORS request (this is using Ionic version 2). In Angular 1, I do something like this.

.factory('LoginService', ['$http', function($http) { 
 var service = {};

 service.isUserLoggedIn = function() {
  var restUrl = '';
  var options = {
   method: 'GET', url: restUrl, withCredentials: true,
   headers: { 
    'x-request-with': 'XMLHttpRequest', 
    'x-access-token': 'sometoken' 
  return $http(options);

 return service;

In Angular 2 using TypeScript, a lot has changed (Promises/Observables). My attempt so far looks like the following.

import { Injectable } from '@angular/core';
import { Headers, Http, Response, RequestMethod, RequestOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Observable';

export class LoginService {
  constructor(private _http:Http) {


  isLoggedIn():boolean {
    var r:any;
    var e:any;
    let url = '';
    let options:RequestOptionsArgs = {
      url: url,
      method: RequestMethod.Get,
      search: null,
      headers: new Headers({
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'x-access-token' : 'sometoken'
      body: null
    this._http.get(url, options).map(this.extractData).catch(this.handleError)
       response => { r = <any>response; console.log(r); }, 
       error => { e = <any>error; console.log(e); });
    return false;

  private extractData(response:Response) {
    let body = response.json();
    return || { };

  private handleError(error:any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.log('error = ' + errMsg);
    return Observable.throw(errMsg);

I am no longer sure how to address in Angular 2 what I had in Angular 1

I did a little bit more searching, and I was able to understand how to insert headers and properly handle the subscription. However, the withCredentials is still a problem.

I found this SO post angular2 xhrfields withcredentials true and modified my constructor as follows. It works now.

constructor(@Inject(Http) private _http:Http) {
    let _build = (<any> _http);
    (<any> _http) = () => {
      let _xhr = _build();
      _xhr.withCredentails = true;
      return _xhr;



The support of withCredentails will be present in the RC2 version of Angular2 that will be released soon. It's not part of the RC1 version... You need to wait a bit.

With RC2, you will be able to use this property directly in the request options:

this.get('...', { withCredentials: true })

See this question for more details:


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.