【问题标题】:Angular 5 - Are callbacks limited in scope? [duplicate]Angular 5 - 回调的范围是否有限? [复制]
【发布时间】:2018-06-21 16:29:26
【问题描述】:

假设您定义了一个如下所示的变量 (snackbar)。 Angular 类的其余部分可以使用this 访问它,但不能在 Promise 的回调中访问。我正在使用 AngularFire 5。

export class SomeComponent implements OnInit {
    constructor(private snackbar: MatSnackBar, private afs: AngularFirestore) {}    

    //Promise function
    this.afs.doc(path).set({
        ...some code
    }).then(function(docRef){
        this.snackbar.open('Snackbar message', 'OK');  //Sanckbar unreachable
    });

    //Regular function
    this.snackbar.open('Snackbar message', 'OK');  //Sanckbar works fine
}

有人如何从then 中获取这些变量?还是根本不可能?

【问题讨论】:

  • function(docRef) 替换为arrow function。您的context 已更改

标签: javascript angular firebase callback promise


【解决方案1】:

这是一个 JavaScript“特性”

使用

 }).then((docRef) =>{

而不是

 }).then(function(docRef){

另见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

【讨论】:

  • 效果很好,谢谢。
  • @FiringBlanks 很高兴听到 :)
  • 这不是 EcmaScript 的功能吗?
  • @trichetriche 我的意思是 this 不能像大多数人期望的那样工作 function () {} 是一个 JavaScript 功能 ;-),你是对的 =>
猜你喜欢
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2016-03-23
  • 2014-10-27
  • 1970-01-01
  • 2019-01-23
相关资源
最近更新 更多