【问题标题】:Property 'token' does not exist on type 'Promise<any>'类型“Promise<any>”上不存在属性“token”
【发布时间】:2018-10-25 05:28:33
【问题描述】:

我想处理一个令牌。但是得到消息:

“Promise”类型上不存在属性“token”

我有以下代码。我得到一个带有属性令牌的 json。顺便说一句,我是由使用 Angular 2 的教程指导的。我已经在没有 ['token'] 的情况下尝试过它。但没有成功。我也有帖子的界面,但我没有使用它来消除错误。它也不适用于界面。

这是我的代码:

signin(email: string, password: string) {
    return this.http.post<any>('http://127.0.0.1:8000/api/userLogin',
      { email: email, password: password },
    this.httpOptions).map((response: Response) => {
      const token =  response.json()['token'];
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace('-', '+').replace('_', '/');
      return JSON.parse(window.atob(base64));
    });

  }

教程:

https://www.youtube.com/watch?v=pT9_FngJuzY&t=321s

顺便说一句,在这种情况下,我使用 laravel / passport。

success:
{token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjllOW…lsJiIWVmiiNY1Ft02MSWGS-Thx7_warYrUucP8bPHHnyMCfnU"}

【问题讨论】:

  • 应该是Response.token
  • 您的 API 响应是什么?
  • 你在哪里打电话和订阅登录?你试过response.json().token; 吗?
  • @Helge,success 是否包含在回复中? API 的响应是这样的 -> success: {token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjllOW…lsJiIWVmiiNY1Ft02MSWGS-Thx7_warYrUucP8bPHHnyMCfnU"} ?
  • 你在某处订阅了吗?

标签: angular token


【解决方案1】:

为什么不使用 Serializable 类。

这是我对这个问题的解决方案,来自:Angular2 HTTP GET - Cast response into full object

export class MdfResponse {
  public message?: string;
  public token?: string;

  constructor() {}

  fromJSON(json) {
    for (var propName in json)
       this[propName] = json[propName];
    return this;
  }
}

当你调用登录函数时

signIn(user: User) { const body = JSON.stringify(user);
      headers: new HttpHeaders({"Content-Type": "application/json"})
      return this.http.post("http://localhost:3000/users/login", body, httpOption)

     .pipe(map((response) => {
          let test = new AIPResponse().fromJSON(response);
          localStorage.setItem("token", test.token);
          localStorage.setItem("userId", test.message);
  }))
     .pipe(catchError((error) => throwError(error)));
  }

希望得到帮助!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2017-08-24
    • 2019-12-26
    • 2017-12-25
    • 2021-02-08
    • 2019-09-20
    • 2018-09-09
    相关资源
    最近更新 更多