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

在Promise函数中调用AngularFirestore时this失效,如何正确调用afs?

解决Promise中无法访问AngularFirestore实例的问题

这个问题的核心是传统function回调里的this指向和组件实例的this不一致,导致你没法通过this.afs访问到注入的AngularFirestore实例。下面给你几种简单可行的解决办法:

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

箭头函数不会创建自己的this,它会继承外层作用域的this,刚好能解决这个问题。同时建议把方法改成Angular组件规范的类方法形式:

import { AngularFirestore } from 'angularfire2/firestore';

constructor(private afs: AngularFirestore) { }

testMethod() {
  const promise = new Promise((resolve, reject) => { // 这里改用箭头函数
    this.afs.collection('profiles'); // 现在this能正确指向组件实例,正常访问afs
    resolve();
  });
  return promise;
};

方法2:提前保存this的引用

在Promise构造函数外面先把组件的this存起来,比如用self或者that,然后在回调里用这个变量访问afs:

import { AngularFirestore } from 'angularfire2/firestore';

constructor(private afs: AngularFirestore) { }

testMethod() {
  const self = this; // 提前保存组件实例的this引用
  const promise = new Promise(function(resolve, reject){
    self.afs.collection('profiles'); // 用self代替this访问afs
    resolve();
  });
  return promise;
};

方法3:给回调函数绑定this

通过bind()方法把回调函数的this强制绑定到组件实例上:

import { AngularFirestore } from 'angularfire2/firestore';

constructor(private afs: AngularFirestore) { }

testMethod() {
  const promise = new Promise(function(resolve, reject){
    this.afs.collection('profiles');
    resolve();
  }.bind(this)); // 绑定this到组件实例
  return promise;
};

另外补充一点:你原始代码里var TestMethod = function()的写法不太符合Angular组件的代码规范,改成类方法的形式(比如上面示例里的testMethod())会更稳妥,也能减少上下文相关的问题。

内容的提问来源于stack exchange,提问作者jrocc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:31:07