You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular HttpClient调用报错:TypeError: 无法读取undefined的get属性

问题:Angular中Stripe回调内调用HttpClient报错"TypeError: Cannot read properties of undefined (reading 'get')"

问题详情:

  • 模块已正确导入HttpClientModule:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';
import { ReactiveFormsModule } from '@angular/forms';
import { HomePageRoutingModule } from './home-routing.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  declarations: [HomePage]
})
export class HomePageModule {}
  • 组件已正确导入并注入HttpClient:
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient, private navCtrl: NavController) {
  Stripe.initialize({
    publishableKey: 'private_key_im_using',
  });
}
  • 直接调用this.http正常,但在StripeCheckout的token回调中调用时触发错误,错误栈显示this.http未定义
  • 服务端接口无问题,用VSCode HTTP客户端可正常访问

核心原因:

传统function定义的回调会改变this的上下文,此时回调内的this指向Stripe的回调执行环境,而非Angular组件实例,因此无法访问组件中注入的http对象。

解决方案:

方案1:使用箭头函数(推荐)

箭头函数会继承外部作用域的this,确保回调内的this指向组件实例:

pay(amount: any) {
  var handler = (<any>window).StripeCheckout.configure({
    key: 'private_key_im_using',
    locale: 'auto',
    token: async (token: any) => { // 替换为箭头函数
      console.log(token);
      this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe((response: any) => {
        console.log(response);
      });
    }
  });

  handler.open({});
}

方案2:提前保存组件的this引用

在pay函数内先将组件实例的this保存到变量中,回调内使用该变量访问组件属性:

pay(amount: any) {
  const componentThis = this; // 保存组件实例的this
  var handler = (<any>window).StripeCheckout.configure({
    key: 'private_key_im_using',
    locale: 'auto',
    token: async function (token: any) {
      console.log(token);
      componentThis.http.get('https://jsonplaceholder.typicode.com/posts').subscribe((response: any) => {
        console.log(response);
      });
    }
  });

  handler.open({});
}

额外提示:

loadStripe方法内的token回调也存在相同的this指向问题,如果后续需要在该回调中调用组件属性,建议同样采用上述两种方法修正。

内容的提问来源于stack exchange,提问作者Hector_o'lector

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:15:49