首页 > 解决方案 > 从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通过从登录名调用来获得后者的分配。

标签: jsonangulartypescript

解决方案


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);
});

推荐阅读