简体   繁体   中英

Form component created once and reused shares the same service

How to prevent component (which is reused) from reusing the same service? How to protect the reused component from sharing the data when the service is used?

Code On editor

1- This is an working example works fine without using service

2- This is not working when a service is used

// sign in component shared

import { Component, OnInit, Input } from '@angular/core';
import { SignInFormService } from '../../services/sign-in-form-create.service';
import { Auth } from '../../services/auth.service';

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

  constructor(private auth: Auth) { }
  @Input() userType: string;
  ngOnInit() {
    this.createForm();
  }

createForm() {
  this.formGroup = this._formBuilder.group({
      username: '',
      password: ''
  });
}

Angular services are singleton. If many components are using the same service, these components will have the same object reference, so if they are using service's variables, they are sharing same references.

In your demo, you are using the same FormGroup in two components, so values are changed everywhere.

There are many ways to fix it.

  1. You could return a new instance of the FormGroup every time, instead of returning the instance stored in your service.

  2. If you want to persist FormGroups in your service, you will have to keep them in a collection and manage instances.

The best way would be to use the formBuilder directly in components instead of services to avoid memory leaks, otherwise you will have to manage your instances

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

   @Input() userType: string;
   formGroup: FormGroup;

   constructor(
       private formBuilder: FormBuilder
   ) {
   }

   ngOnInit() {
       this.formGroup = this._formBuilder.group({
            username: '',
            password: ''
       });
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM