angular5 - Angular 5中的RequestOptions不推荐使用符号错误
问题描述
我正在尝试将 Angular 4 中的代码调整为 Angular 5。我做了很多更改,但我有一个关于RequestOptions
. 该代码是关于身份验证的,这是我遇到错误的地方:
import { Injectable } from '@angular/core';
import { RequestOptions} from '@angular/http';
import {User} from '../model/model.user';
import 'rxjs/add/operator/map';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable()
export class AuthService {
constructor(public http: HttpClient) { }
public logIn(user: User) {
const headers = new HttpHeaders();
headers.append('Accept', 'application/json')
// creating base64 encoded String from user name and password
const base64Credential: string = btoa( user.username + ':' + user.password);
headers.append('Authorization', 'Basic ' + base64Credential);
// this is where i'm having a problem :
const httpOptions = new RequestOptions();
httpOptions.headers = headers;
return this.http.get('http://localhost:8081/' + '/account/login' ,
httpOptions)
.map(resp => {
// login successful if there's a jwt token in the response
const user = resp.json().principal; // the returned user object is a principal object
if (user) {
// store user details in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logOut() {
// remove user from local storage to log user out
return this.http.post('http://localhost:8081/' + 'logout', {} )
.map(resp => {
localStorage.removeItem('currentUser');
});
}
}
错误:使用了不推荐使用的符号,请帮助我更改 Angular 5 中的代码(RequestOptions
)
解决方案
您不应该使用RequestOptions
已弃用的模块@angular/http
。
如API 文档中所示options
,现在属于以下类型:
{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; }
因此你应该写:
const headers = new HttpHeaders();
headers.append('Accept', 'application/json')
const base64Credential: string = btoa( user.username + ':' + user.password);
headers.append('Authorization', 'Basic ' + base64Credential);
this.http.get('http://localhost:8081/' + '/account/login', {
headers: headers
});
或者:
this.http.get('http://localhost:8081/' + '/account/login', {
headers: {
'Accept': 'application/json',
'Authorization': 'Basic ' + btoa(user.username + ':' + user.password)
}
});
推荐阅读
- java - 具有一个元素的 LinkedBlockingQueue - 读取器/写入器竞争条件
- node.js - chat.postMessage 的问题 - channel_not_foud
- r - 获取 RandomForest 中单个树的重要性
- assembly - 从 8086 emu 读取一个字符串并输出回来
- c# - 将文本框值传递给 sql 查询 c# 应用程序
- vba - Word 表查找分段符,将行内容分成两行
- c - 如何使用 OpenSSL 库生成大素数?
- python - 使用beautifulsoup将字符串作为列表放入一行
- python - 反向未找到
- tensorflow - 是否有 dnnlib 的任何文档:NVlabs 项目中的附加库?