我是Angular的新手,我正在尝试调用REST服务来获取将用于填充注册页面下拉列表的组织列表。我的登录页面工作正常,我得到一个令牌并将其存储在localStorage中。基于console.log()语句,在注册流程中,此标记也会被检索,但它不会在请求的标头中传递。这是chrome dev工具的标题列表。 enter image description here
这是我的http.service.ts
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
@Injectable()
export class HttpService {
constructor (public http: Http) {}
createAuthorizationHeader(headers: Headers) {
console.log('HttpService createAuthorizationHeader called');
let tok = JSON.parse(localStorage.getItem('currentUser')).token;
console.log(tok);
//headers.append('X-Authorization', 'Bearer ' + tok);
headers.set('X-Authorization', 'Bearer ' + tok);
}
get(url) {
let headers = new Headers();
console.log('HttpService get called- ' + url);
this.createAuthorizationHeader(headers);
/* let tok = JSON.parse(localStorage.getItem('currentUser')).token;
console.log(tok);
//headers.append('X-Authorization', 'Bearer ' + tok);
headers.set('X-Authorization', 'Bearer ' + tok);*/
let options = new RequestOptions({ headers: headers });
console.log(headers.toJSON());
return this.http.get(url, options).map(res => res.json());
}
post(url, data) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, {
headers: headers
});
}
}
这就是我的称呼方式
import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import {HttpService} from './http.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Organization} from '../../model';
@Injectable()
export class OrganizationService implements OnInit {
orgs: Organization[];
constructor(private http: HttpService) { this.http = http}
ngOnInit() {
console.log('ngOnInit OrganizationService called.');
}
getOrganizations(): any {
console.log('getOrganizations OrganizationService called.');
// get the token here from localstorage and add to header.
return this.http.get('http://localhost:9966/api/getOrganizations')
.subscribe(result => {
console.log( result );
});
/* .map((res) => {
console.log('got http response');
console.log(res.json());
return res.json();
} );*/
//return this.orgs;
}
}
问题是' X-Authorization'标头值不随请求传递。这就是服务器发回401状态的原因。我也尝试使用RequestOptions,仍然是同样的问题。感谢您的任何帮助
答案 0 :(得分:0)
重写答案以适合您的结构。
<强> HttpService的:强>
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";
@Injectable()
export class HttpService {
constructor(private http: Http) { }
createAuthorizationHeader(): Headers {
let tok = 'My token';
return new Headers({ 'X-Authorization': `Bearer ${tok}` })
}
get(url): Observable<any> {
return this.http.get(url, { headers: this.createAuthorizationHeader() }).map(res => res.json());
}
}
<强> OrganizationService 强>:
import { Observable } from "rxjs/Observable";
import { Injectable } from '@angular/core';
import { RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { HttpService } from './http.service';
@Injectable()
export class OrganizationService {
constructor(private httpService: HttpService) { }
getOrganisations(): Observable<any> {
return this.httpService.get('/api/organizations');
}
}
<强> SignupComponent 强>:
import { Component, OnInit } from '@angular/core';
import { OrganizationService } from '../organization.service';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
constructor(private orgranizationService: OrganizationService) { }
ngOnInit() {
this.orgranizationService.getOrganisations().subscribe(resp =>
console.log(resp));
}
}
答案 1 :(得分:0)
您正在使用RequestOptions,但get方法需要RequestOptionsArgs。只需将您的代码更改为:
get(url) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
let options = { headers: headers }; // HERE
return this.http.get(url, options)
.map(res => res.json());
}
答案 2 :(得分:0)
感谢Markus和LLL的帮助。我想我弄清楚发生了什么。 CORS在行动中。 我使用Chrome进行测试,Chrome更安全,发送飞行前OPTIONS请求,其中不包含我添加的标头。我不得不在服务器端处理OPTIONS请求,不回复401.现在Chrome正在发送第二个请求(在OPTIONS成功之后),并使用正确的标头。
来自IE的测试与原始服务器端代码一起工作正常。 :)