json - 从Angular4中的[object object]获取值
问题描述
这是我最后一个问题的代码:
getUserRole() {
const headers = new Headers();
headers.append('Authorization', `Bearer ${this.getToken()}`);
console.log(this.getToken());
const options = new RequestOptions({ headers: headers});
return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options).pipe(map(res => res.json()))
.subscribe(data => {
this.userRole = JSON.stringify(data);
if (this.userRole === 'parent') {
this.logout();
} else if (this.userRole === 'school') {
this.isUser = true;
this.isAdmin = false;
this.cookieService.set('isSchool', '1');
} else if (this.userRole === 'admin') {
this.isUser = false;
this.isAdmin = true;
this.cookieService.set('isAdmin', '1');
}
});
}
但是当我userRole
在调用这个函数后尝试访问时,我得到userRole undefined
了,可能是因为它在.subscribe
被击中之前被返回了。
结果我得到这个undefined
:
var result = this.getUserRole(token);
console.log('Call from login ' + result);
所以,我改变了方法是这样的:
getUserRole(roletoken: string) {
const headers = new Headers();
headers.append('Authorization', `Bearer ${roletoken}`);
const options = new RequestOptions({ headers: headers});
var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).pipe(map(res => res.json()));
console.log(result);
return result;
}
但在这里我得到result
了[object object]
。
我可以知道我应该采用哪种方法来立即userRole
通过任何一种方法分配。
在第二种方法中,我无法转换[object object]
为值。
我从 API 收到的数据是这样的:
["school"]
这是召唤:
this.getUserRole(token);
console.log('Call from login ' + this.userRole);
这是内部getUserRole
函数:
var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).subscribe(data => {
this.userRole = JSON.stringify(data);
console.log(data);
});
这是我得到的控制台序列:
从登录名调用未定义
响应 {_body: "["school"]", status: 200, ok: true, statusText: "OK", headers: Headers, ...}
因此,即使尝试使用 subscribe 的代码,userRole
通过从登录名调用来获得后者的分配。
解决方案
getUserRole
返回一个Observable
. 如您所见,您需要使用subscribe
它来进行 HTTP 调用并接收数据。由于您使用的是旧Http
类而不是HttpClient
,因此您需要将响应转换为实际的 JSON 数据。下面的代码应该可以工作:
getUserRole(roletoken: string) {
const headers = new Headers();
headers.append('Authorization', `Bearer ${roletoken}`);
const options = new RequestOptions({ headers: headers});
return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).pipe(map(response => response.json()));
}
了解Observables
和 HTTP 请求的异步性质很重要。this.userRole
仅在请求完成后设置。因此,如果你想用它做某事this.userRole
并想确定它有一个值,你应该在 subscribe 函数中使用它:
this.getUserRole(token).subscribe(userRole => {
this.userRole = userRole;
console.log('Call from login ' + this.userRole);
});
推荐阅读
- openbmc - 如何在 Openbmc 中访问 Redfish(https://xxx.xxx.xxx:8000/redfish/v1)
- java - Barcode Google Vision API 检查检测到的条形码是否在区域内
- sql-server - SSIS:在活动批处理中部署时不支持的脚本任务版本 15.0 脚本
- sql - 使用 REGEX_CONTAINS 搜索带有撇号 (') 的值
- reactjs - 带有反应钩子的 Apollo graphql 突变轮询
- python - 比较 numpy 数组中的多边形
- wso2 - WSO2 Integrator:REST API GET 请求缺少响应正文
- python - 如何在包含多值项的数据框列中获取值
- java - 在动作侦听器中将当前 JFrame 的引用传递给 JDialog
- ruby-on-rails - 上限生产部署 - Rails 6 - 失败