这是我上一期提问的代码:
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“]”,状态:200,ok:true,statusText: “OK”,标题:标题,...}
因此,即使尝试使用订阅代码,userRole
的分配也是通过登录调用来获得的。
答案 0 :(得分:2)
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);
});
答案 1 :(得分:0)
我会做的是, 如果你的休息api发给你一个json
userRole: UserRole // here you set the type of userRole as UserRole that you defined earlier or in an other file
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<UserRole>(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options)
.subscribe(data => {
this.userRole = 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');
}
});
}
如果你的api发给我一个json的列表我会做的,(它可以是一个json的列表,如[{name:'name',first_name:'first_name'}])
userRole: UserRole // here you set the type of userRole as UserRole that you defined earlier or in an other file
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<UserRole[]>(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options)
.subscribe(data => {
this.userRole = data[0]; // of course here if you want them all you will make a loop and use this.userRoles set as userRoles: UserRole[]
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');
}
});
}
看起来你的api不会给你一个json,如果它真的能给你类似的东西 ['学校'] 而不是[{role:'school'}]之类的东西 我会试试
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[0]); // data is a list you take the first element
if (this.userRole === 'parent') {
this.logout();
} else if (this.userRole === 'school') {
// same
}
或
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); // data is a list you take the first element
if (this.userRole[0] === 'parent') {
this.logout();
} else if (this.userRole[0] === 'school') {
// same but you take the first element of the list
}
我不确定过去的2,因为我曾经从我的apis得到json的回应,但这是我第一次检查并看到我得到的
不要忘记你可以使用浏览器调试器在每一步调试并查看变量的值,就像你在chrome中一样,只需在函数开头设置断点并遵循它;)