首页 > 解决方案 > Angular 7, nested function using same variable

问题描述

I'm trying to run one function - "createThreeDates()" that can generate three different results (dates based on -90, -60, -45), using the same variable. After a user sets a date in the input field, that date variable is set and used in the function. The Generate 1 button calls the function. Everything works fine if I only needed one date (not three). FYI, this function uses the installed/import package "add-subtract-date."

There are NO ERRORS in my code, but the function returns the SAME date (fortyDaysDate) to all three input fields in the browser (?). -I don't know how this is possible when I have different ngModels.

Here is component.ts...

    import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
    import { CalculatorService } from '../calculator.service';
    import { add, subtract } from 'add-subtract-date';
    import { NgForm, FormGroup } from '@angular/forms';


    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {

      public fortyDaysDate: any;
      public sixtyDaysDate: any;
      public ninetyDaysDate: any;



      private _retireSet: Date;
      @Input() set retireSet(date: Date) {
        this._retireSet = new Date(date);
      }

    constructor(private calculatorService: CalculatorService) { 
      }

      ngOnInit() {
      }

    public createThreeDates(): void {
      let d: Date = this._retireSet;
      let ninetyDaysBack = subtract(d, 90, "days");
      this.ninetyDaysDate = ninetyDaysBack;
  console.log('90 is ' + this.ninetyDaysDate);

        let sixtyDaysBack = add(d, 30, "days");
        this.sixtyDaysDate = sixtyDaysBack;
        console.log('60 is ' + this.sixtyDaysDate);

         let fortyDaysBack = add(d, 15, "days");
         this.fortyDaysDate = fortyDaysBack;
         console.log('45 is ' + this.fortyDaysDate);

// the value of sixtyDaysDate changes to fortyDaysDate value here...
         console.log('60 is ' + this.sixtyDaysDate);

        }
    }

    }

Here is component.html...

 <div class="container">
    <form class="ret-form" #calcForm="ngForm" novalidate (ngSubmit)="onSubmit(calcForm)">

    <div class="form-group">
        <label for="retireSet">Set Date</label>
        <input type="datetime-local" id="retireSet" name="RetireCalculatorSetDate" value="retireSet" 
        ngModel #RetireCalculatorSetDate="ngModel" [(ngModel)]="retireSet" class="form-control" />
    </div>

    <div>
 <button type="button" class="btn btn-lg btn-outline-dark" (click)="createThreeDates()">Generate 1</button>      

    <div>
  <input type="text" name="RetireCalculatorDay90" value="ninetyDaysDate" ngModel #RetireCalculatorDay90="ngModel" 
  [(ngModel)]="ninetyDaysDate" class="form-control" />
    </div>

    <div>
  <input type="text" name="RetireCalculatorDay60" value="sixtyDaysDate" ngModel #RetireCalculatorDay60="ngModel" 
  [(ngModel)]="sixtyDaysDate" class="form-control" />
    </div>

  <input type="text" name="RetireCalculatorDay45" value="fortyDaysDate" ngModel #RetireCalculatorDay45="ngModel" 
[(ngModel)]="fortyDaysDate" class="form-control" />
    </div>


    </form>
    </div>

标签: angularangular7

解决方案


这更像是一个代码审查而不是一个答案。 您的语法在这里不正确。

  • 删除函数内部的花括号。
  • 确保函数“减法”没有改变传入的变量。您可能想要“克隆”变量“_retireSet”,这样就不会在这个函数中改变它。
  • 如果您不重新分配变量,请使用“const”。在此功能中,您需要使用“让”。
  • 正如@crashmstr 所说,将函数返回类型更改为 void

旁注:函数名称令人困惑。“getAllDates”这意味着您正在返回一个带有日期的对象。而是将名称更改为 prepareAllDates 或 createAllDates 或类似名称。

请记住,“Set”和“Get”分别意味着“Setting a Variable”和“Getting a Variable”。

**更新** 从您下面的评论来看,您似乎遇到了 javascript 本身的问题。

按值分配

var batman = 7;
var superman = batman;   //assign-by-value
superman++;
console.log(batman);     //7
console.log(superman); //8

按引用分配

var flash = [8,8,8];
var quicksilver = flash;   //assign-by-reference
quicksilver.push(0);
console.log(flash);        //[8,8,8,0]
console.log(quicksilver); //[8,8,8,0]

对于您的具体问题:

var x = new Date()

var y = new Date(x)

x.setFullYear('2019');

x //Date 2019-11-01T13:59:56.083Z
y //Date 2018-11-01T13:59:56.083Z

推荐阅读