首页 > 解决方案 > 如何以角度更新类变量中的数据

问题描述

我创建了示例注册应用程序,我需要将这些数据存储在类数据模型中这是我创建的类模型

export class Model {
  name: string;
  tableData: any[];

  constructor() {
    this.tableData = [];
}
// this.tableData = [
//   {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
//   {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
//   {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
//   {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
//   {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
//   {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
//   {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
//   {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
//   {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
//   {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
// ];
}

这是我的组件.ts

import { Component, EventEmitter, Output } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Model } from '../model';
@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent {
  model: any;
  temp: any;
  // tslint:disable-next-line:variable-name
  constructor(private router: Router) { }
  // @Output() dataEvent = new EventEmitter();

  registraion_data = [];
  data = [];
  firstname = new FormControl('', [
    Validators.required,
    Validators.minLength(5),
  ]);
  lastname = new FormControl('', [
    Validators.required,
    Validators.minLength(5),
  ]);
  email = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);
  // tslint:disable-next-line:variable-name
  mob_no = new FormControl('', [
    Validators.required,
  ]);
  pswd = new FormControl('', [
    Validators.required,
  ]);

  fn_submit() {
    this.data.push(this.firstname.value);
    this.data.push(this.lastname.value);
    this.data.push(this.email.value);
    this.data.push(this.mob_no.value);
    this.data.push(this.pswd.value);

    this.registraion_data.push(this.data);
    this.data = [];
    console.log(this.registraion_data);
    this.model = new Model();
    console.log(this.model.name);
    this.temp =
      {
        name: this.firstname.value,
        lname: this.lastname.value,
        email: this.email.value,
        phoneNo: this.mob_no.value,
        password: this.pswd.value
      };
    this.model.tableData.push(this.temp);
    // this.router.navigate(['/login']);
    this.router.navigate(['/login'], { queryParams: this.registraion_data });
  }

}

这里我导入了类模型并使用类对象添加了值。这些值仅在此组件中更新。当我将该类导入另一个组件时,模型数据为空。我需要更新数据,所以模型可以在全球范围内使用。

标签: angular

解决方案


当您编写时,this.model = new Model()您正在使用其初始数据创建 Model 类的新实例。

如果您想在所有组件之间持久化数据,那么您需要将 Model 类设为“单例”,因此您只能创建它的一个实例并在应用程序范围内使用它。

Angular 服务是开箱即用的单例,因此您可以使用服务来保留 Model 值并将数据添加到其中并从任何组件访问它。


推荐阅读