javascript - 类型错误 : Cannot read property 'http' of undefined

标签 javascript angular rest http typescript

我试图将其放入我的其余 API 中,但我不断收到 TypeError。

import { Component, OnInit, Inject, Injectable } from '@angular/core';
import { AuthService } from "../core/auth.service";
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import * as firebase from 'firebase/app'; //Firebase SDK

@Injectable()
export class LoginService implements OnInit {

  constructor(public auth: AuthService, private http: HttpClient) {

  }
  ngOnInit() {
  }

  lastLogin() {
    firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
      // Send token to your backend via HTTPS
      //console.log(idToken);
      const req = this.http.put('https://dev-api.byrd.news/v1/login', {
        user_token: idToken
      })
      .subscribe(
        res => {
          console.log(res);
        },
        err => {
          console.log("error skete");
        }
      );
    });

  }
}

我调用该函数只是为了记录用户的最后登录时间,即日期以及是否成功。 通过 firebase 执行此操作,根据文档我应该收到一个 idToken:https://firebase.google.com/docs/auth/admin/verify-id-tokens

我做错了什么?

最佳答案

在这一行:

firebase.auth().currentUser.getIdToken(true).then(function(idToken) {

将匿名函数更改为箭头函数:

firebase.auth().currentUser.getIdToken(true).then((idToken) => {

这将使 this 成为函数内 LoginService 的实例。

关于javascript - 类型错误 : Cannot read property 'http' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171359/

相关文章:

javascript - Vanilla JS Web 组件中的外部依赖项位于何处?

html - 未定义的 Angular 错误 “Cannot read property ' firstName'”

angular2-highcharts : update rendered chart data

java - Android 上的 ReSTLet 是否可以移植到 Java SE/EE?

java - RESTful Web 服务的返回值,考虑空值

python - 在 REST API 中填充 ManyToMany 字段值时严重影响性能(使用 django REST 框架)

javascript - Google map API,MarkerClusterer 可以显示有关集群内项目的信息吗?

javascript - 为什么我的字符串返回 "'"

javascript - 无法在 Typescript 中提取对象值

angular - 如何在 Angular 2(路由器 3)中处理租户子域