Angular 从函数中设置变量

Angular 从函数中设置变量,angular,typescript,Angular,Typescript,这可能是一个简单的问题/答案,但我似乎无法理解: 我正在使用AbstractControl的函数验证字段: errorVar: boolean = false function(c: AbstractControl): {[key: string]: string } | null { // validation if 'test' is true or not goes here if(test) { let errorMessageText: "test" return {'e

这可能是一个简单的问题/答案,但我似乎无法理解: 我正在使用AbstractControl的函数验证字段:

errorVar: boolean = false

function(c: AbstractControl): {[key: string]: string } | null {
 // validation if 'test' is true or not goes here
 if(test) {
  let errorMessageText: "test"
  return {'errorText': errorMessageText};
 }
return null;
}

除了
errorText
之外,如果函数返回null,我希望函数还将变量
errorVar
设置为
true
false

您可以这样做:

  errorVar: boolean = false

  function(c: AbstractControl): { [key: string]: string } | null {
    // validation if 'test' is true or not goes here
    if (test) {
      this.errorVar = true;
      let errorMessageText:
        return { 'errorText': errorMessageText };
    }

    this.errorVar = false;
    return null;
  }
var errorVar: boolean = false;

function(c: AbstractControl): {[key: string]: string } | null {
    // validation if 'test' is true or not goes here
    if(test) {
        errorVar = true;
        let errorMessageText: string ="test";
        return {'errorText': errorMessageText};
    }
    errorVar = false;
    return null;
}

我认为有几个问题

  • 您的
    errorVar
    应该使用
    var
    let
    声明,以便您可以通过闭包在函数中设置它
  • 必须使用
    =
    设置
    errorMessageText
    变量,而不是
像这样:

  errorVar: boolean = false

  function(c: AbstractControl): { [key: string]: string } | null {
    // validation if 'test' is true or not goes here
    if (test) {
      this.errorVar = true;
      let errorMessageText:
        return { 'errorText': errorMessageText };
    }

    this.errorVar = false;
    return null;
  }
var errorVar: boolean = false;

function(c: AbstractControl): {[key: string]: string } | null {
    // validation if 'test' is true or not goes here
    if(test) {
        errorVar = true;
        let errorMessageText: string ="test";
        return {'errorText': errorMessageText};
    }
    errorVar = false;
    return null;
}

你的问题是什么?如果我试图在函数中设置变量,它会返回“undefined不是一个对象。所以我对这一点相当陌生,也不知道为什么。所以我的想法是让函数返回variableNope,当然,首先尝试了。它返回“undefined不是一个对象”“是否在
类的上下文中定义了
errorVar
?是的,它是-它是一种被动形式,变量定义和函数在导出类中谢谢您的回答,但这不是它不起作用的原因。
errorVar:boolean=false
是我在类的前面声明变量的指针;函数是我想要实现的一种表示,而不是一段正常工作的代码。不是说我能解释它,但请放心,我还有大约20个其他的声明,它们以这种方式工作得很好。。。第二点,TypeScript让我们在变量名后使用冒号来定义变量类型
let errorMessageText:“test”
不起作用(
errorMessageText
未定义),但
let errorMessageText=“test”
起作用。关于“指针”的事情,你可以做的是将一个对象作为参数传递,并在函数中修改它的属性。当然它没有,因为正如我前面所说的,您用冒号“:”定义变量的类型,并用等号“=”写入。因此,在本例中,我将
errorMessageText
设置为类型字符串。。。。但所有这些都无关紧要,因为函数正确地返回
errorMessageText
,所以我需要的是函数返回第二个变量!好的,这是一个打字错误。是不是因为
这个
绑定有问题,阻止您设置
errorVar
(如果它是在类中声明的)?在这种情况下,可以通过传递
myFunction.bind(myInstance)
而不是
myFunction
来显式绑定。不管怎样,祝你好运。