2016-05-31 22 views
0

您能否告诉我如何在我的Angular 2请求中设置'withCredentials = true'?
在Angular 1中,它工作正常如下:Angular 2:使用凭证,x域名设置

x域设置和使用凭据设置。

var chat = angular.module('chat',[]) 
//configuration for cord 
chat.config(function($httpProvider) { 
//Enable cross domain calls 
$httpProvider.defaults.useXDomain = true; 
//allow credentials 
$httpProvider.defaults.withCredentials = true; 
}); 

功能的角1

//http-structure 
    this.structureDataRequest = function() { 
    $http({ 
    method: 'POST', 
    //graph url 
    url: 'http://manny.herokuapp.com/audit/get/structure', 
    header: {'Content-Type': 'application/json'} 
    }).success(function (response) { 
    dataReceived = response.content; 
    buildDiagram.buildDiagramm(); 
    }) 
    }; 

角2代码,以使X-域;这需要修改设置withCredentials=true

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

@Injectable() 
    export class StructureRequestService { 
    result: Object; 
    constructor (private http: Http) {} 
    private structureUrl = 'http://manny.herokuapp.com/audit/get/structure'; // URL to structure APi 
    sendRequest() { 
     let headers = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: headers }); 
     return this.http.post(this.structureUrl,options) 
       .map((res: Response) => res.json()) 
       .subscribe(res => {this.result = res; 
     console.log(this.result)}); 
     } 
    } 

替代版本(仍然不工作)

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

@Injectable() 
export class StructureRequestService { 
result: Object; 
constructor (private http: Http) {} 
private myUrl = 'http://manny.herokuapp.com/audit/get/structure'; // URL to structure APi 
sendRequest() { 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ 
     headers: headers, 
     withCredentials: true 
    }); 
    return this.http.post(this.myUrl,options) 
     .map((res: Response) => res.json()) 
     .subscribe(res => {this.result = res; console.log(this.result)}); 
} 
} 

回答

0

正如你在Angular 2 docs检查 - RequestOptions类型包含withCredentials场应设置到true在你的exapmle。不幸的是,我不能在那里看到useXDomain参数。

+0

你好伴侣,像这样:??发送请求(){ let headers = new Headers({'Content-Type':'application/json'});允许选项=新的请求选项({标题:标题, withCredentials:true }); return this.http.post(this.structureUrl,options) .map((res:Response)=> res.json()) .subscribe(res => {this.result = res; console.log (this.result)}); } – Serhiy

+0

'withCredentials'是最近添加的,AFAIK尚未包含在RC.1中,但可能会与下一次更新。已经有其他答案显示如何使用'withCredentials'。 –

相关问题