如何在Ionic中使用CORS编写Angular 2服务? [英] How do I write an Angular 2 service with CORS in Ionic?

查看:198
本文介绍了如何在Ionic中使用CORS编写Angular 2服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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)。到目前为止,我的尝试如下所示。

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';

@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中有什么

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

  • withCredentials (note that https://angular.io/docs/js/latest/api/http/index/RequestOptionsArgs-interface.html#!#withCredentials-anchor says the RequestOptionsArgs should have a field withCredentials but I get an error in the IDE Visual Studio Code saying that it does not exists in the interface; ionic is probably using an older angular 2 version?)
  • headers (x-request-with and x-access-token)
  • the actual response

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

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.

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

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)._backend._browserXHR.build;
    (<any> _http)._backend._browserXHR.build = () => {
      let _xhr = _build();
      _xhr.withCredentails = true;
      return _xhr;
    }
  }


推荐答案

支持 withCredentails 将出现在即将发布的Angular2的RC2版本中。它不是RC1版本的一部分...你需要等一下。

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.

使用RC2,你可以直接在请求选项中使用这个属性: / p>

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:

  • Angular 2 - http get withCredentials

这篇关于如何在Ionic中使用CORS编写Angular 2服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆