最近我遇到了一些标题小问题,并收到了REST API传递的数据。所以这是我的UserService,方法是getUserData,它向API发送带有Authenticated User令牌的头,服务器检查它是否正确,并传递应该收到的用户数据:'Content-Type', 'application/json'
好的,这是angular2 UserService
import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import { User } from '../../models/user';
@Injectable()
export class UserService {
public apiUrl: string = 'http://127.0.0.1:8000/api'; // without a slash
public userData: any = localStorage.getItem('currentUser');
public token:any = JSON.parse(this.userData);
public result: any;
private headers: any;
private request: any;
private handleError:any = 0;
constructor( private http: Http, private route: ActivatedRoute ) {}
getUserData():Promise<Array<User>>{
this.headers = new Headers();
this.headers.append('Authorization', 'Bearer {'+ this.token.token +'}');
this.headers.append('Content-Type', 'application/json');
this.request = new RequestOptions({headers:this.headers});
return this.http.get( this.apiUrl + "/get/active/user-data/", this.request)
.toPromise()
.then(( response ) => {
console.log(response.json());
debugger;
return response.json().data as User[];
})
.catch(this.handleError);
}
}
以下是此代码的结果:
这里是发送标题:
和api:
public function showUserData(Request $request)
{
$user = $request->header('Authorization');
return response()->json(self::getAuthenticatedUser($user));
}
我在邮差中检查过这一切,一切都还好......:)
答案 0 :(得分:0)
我尝试了一些变化,它对我有用。让我们尝试下面的方法。
import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import { User } from '../../models/user';
@Injectable()
export class UserService {
public apiUrl: string = 'http://127.0.0.1:8000/api'; // without a slash
public userData: any = localStorage.getItem('currentUser');
public token:any = JSON.parse(this.userData);
public result: any;
private headers: any;
private request: any;
private handleError:any = 0;
constructor( private http: Http, private route: ActivatedRoute ) {}
getUserData():Promise<Array<User>>{
private globalHeaders: Headers = new Headers();
globalHeaders.append('Content-Type','application/json');
globalHeaders.append('Authorization', 'Bearer {'+ this.token.token +'}');
return this.http.get( this.apiUrl + "/get/active/user-data/", {headers: this.globalHeaders})
.toPromise()
.then(( response ) => {
console.log(response.json());
debugger;
return response.json().data as User[];
})
.catch(this.handleError);
}
}