【问题标题】:How do we compensate for the 'elvis operator' inside of an expression?我们如何补偿表达式中的“elvis operator”?
【发布时间】:2017-02-17 06:53:33
【问题描述】:

从 Firebase 绑定到我的数据需要使用 elvis operator,否则一切都会返回 undefined。我刚刚开始使用响应式表单并实现了一个我使用来自 fireBase 的实际数据创建的组件,现在我从 FormGroup 收到一个 undefined 错误,看起来像这样

createForm() {
    this.quesForm = this.fbuild.group({
        question: this.featureQuestion.question,
        id      : this.featureQuestion.id,
        name    : this.featureQuestion.name,
        answers : this.fbuild.array([])
    });
    this.setAnswers(this.featureQuestion.answers);
}

如果我添加 elvis operator 使其像这样

createForm() {
    this.quesForm = this.fbuild.group({
        question: this.featureQuestion?.question,
        id      : this.featureQuestion?.id,
        name    : this.featureQuestion?.name,
        answers : this.fbuild.array([])
    });
    this.setAnswers(this.featureQuestion?.answers);
}

我收到更多错误,告诉我它需要一个表达式和或 ;, 每隔一行。因此,在此处添加 ? 显然与在模板中添加的效果不同。我该如何解决这个问题?

【问题讨论】:

  • elvis 运算符目前仅在视图绑定中受支持(来自 Angular 的特殊支持)。有计划在 TypeScript 中实现它,但还没有完成。
  • 你可以改用question: this.featureQuestion && this.featureQuestion.question

标签: angular typescript firebase firebase-realtime-database angular2-forms


【解决方案1】:

这是 JavaScript(以及 TypeScript 的扩展)中三元运算符的正确用法:

conditionToEvaluate ? valueIfTrue : valueIfFalse

对于您的情况,您必须这样做:

this.quesForm = this.fbuild.group({
    question: this.featureQuestion ? this.featureQuestion.question : '',
    id      : this.featureQuestion ? this.featureQuestion.id : '',
    name    : this.featureQuestion ? this.featureQuestion.name : '',
    answers : this.fbuild.array([])
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多