如何在Ionic中使用CORS编写Angular 2服务?

时间:2016-06-15 02:13:26

标签: javascript typescript angular ionic2 angular-http

我无法使用http将Angular 1 JavaScript服务移动到Angular 2 TypeScript服务来发出CORS请求(这是使用Ionic版本2)。在Angular 1中,我做了类似的事情。

angular.module('app.services',[])
.factory('LoginService', ['$http', function($http) { 
 var service = {};

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

 return service;
}])

在使用TypeScript的Angular 2中,已经发生了很多变化(Promises / Observables)。到目前为止,我的尝试如下所示。

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

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

  }

  isLoggedIn():boolean {
    var r:any;
    var e:any;
    let url = 'http://10.10.10.25:8080/api/user/isloggedin';
    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)
      .subscribe(
       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 body.data || { };
  }

  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);
  }
}

我不再确定如何在Angular 2中解决我在Angular 1中所拥有的内容

我做了一些搜索,我能够理解如何插入标题并正确处理订阅。但是,withCredentials仍然是个问题。

我发现了这个帖子angular2 xhrfields withcredentials true并修改了我的构造函数,如下所示。它现在有效。

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

1 个答案:

答案 0 :(得分:1)

module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-resource/angular-resource.js', 'packages/custom/ecdreport/public/controllers/ecdreport.js', // 'packages/custom/ecdreport/public/routes/ecdreport.js', // 'packages/custom/ecdreport/public/services/ecdreport.js', //'packages/custom/ecdreport/public/views/index.html', 'packages/custom/ecdreport/test/Spec/controllers/ecdreport.js', ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, plugins: [ 'karma-jasmine', 'karma-webpack', 'karma-ng-html2js-preprocessor', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-requirejs', 'karma-coverage', 'karma-junit-reporter' ], // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }; 的支持将出现在即将发布的Angular2的RC2版本中。它不是RC1版本的一部分...你需要等一下。

使用RC2,您可以直接在请求选项中使用此属性:

withCredentails

有关详细信息,请参阅此问题: