как сохранить безопасность клиента при переходе на другой компонент с помощью Angular 6 - PullRequest
0 голосов
/ 08 октября 2018

У меня есть 2 разных компонента, которые перемещаются друг в друга.Как и в этой демоверсии

  1. , я создаю счет, выбираю имя клиента, имя-счета-фактуру и описание, и в конце нажимаю Добавить продукт.
  2. Я добавляю продукт,и перейдите в компоненте счета.Когда я перемещаюсь по счету, имя клиента удаляется.

Для других данных в компоненте счета-фактуры I решение, но для клиента у меня есть проблема.

Создайте службу данных, например кодниже:

export class DataService {
  _data = new Map<string, any>();

  setData(key, value) {
    this._data.set(key, value);
  }

  getData(key) {
    return this._data.get(key);
  }

  clear() {
    this._data = new Map<string, any>();
  }
}

И в InvoiceComponent напишите этот код:

export class AutocompleteDisplayExample implements OnInit {
  clientid: number;
    selectedClient: User;
  addsale: FormGroup;
  products: Array<Products> = [];
  myControl = new FormControl();
   id_client: FormControl = new FormControl();
  options: User[] = [
    { id_client: '1', name: 'Mary', phone: '654987' },
    { id_client: '2', name: 'Shelley', phone: '123456' },
    { id_client: '3', name: 'Igor', phone: '00365987' }
  ];
  filteredOptions: Observable<User[]>;

  constructor(
    public service: Service,
    private fb: FormBuilder,
    private router: Router,
    private dService: DataService
  ) {
    let invoice = '';
    if (this.dService.getData('invoice')) {
      invoice = this.dService.getData('invoice');
    }
    let description = '';
    if (this.dService.getData('description')) {
      description = this.dService.getData('description');
    }
    let id_client = '';
    if (this.dService.getData('id_client')) {
      id_client = this.dService.getData('id_client');
    }

    this.addsale = this.fb.group({
      'invoice_number': new FormControl(invoice, Validators.required),
      'description': new FormControl(description, Validators.required),
      'id_client': new FormControl(id_client, Validators.required)
    });

  }

  ngOnInit() {
    this.filteredOptions = this.id_client.valueChanges
      .pipe(
        startWith<string | User>(''),
        map(value => typeof value === 'string' ? value : value.name),
        map(name => name ? this._filter(name) : this.options.slice())
      );
    this.allproducts();
    this.service.productList.subscribe(productList => {
      this.products = productList;
      this.addsale.controls.Subtotal.setValue(this.subtotal)
    });
  }

  get subtotal() {
    return this.products
      .map(p => p.price * p.quantity)
      .reduce((a, b) => a + b, 0);
  }
  allproducts() {
    this.products = this.service.getProduct();
  }

  displayFn(user?: User): string | undefined {
    return user ? user.name : undefined;
  }

  private _filter(name: string): User[] {
    const filterValue = name.toLowerCase();
    return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
  }


  updateClient(ev: any, idd: any, componentid: any) {
    if (ev.isUserInput) {
      if (componentid === 'id_client') {
        this.clientid = idd;
        console.log('idd', idd)
        this.addsale['controls']['id_client'].setValue(ev.source.value);
      } else {
        console.log('ooops');
      }
    }
  }
  saveData() {
    this.dService.setData('invoice', this.addsale.get('invoice_number').value);
    this.dService.setData('description', this.addsale.get('description').value);
    this.dService.setData('id_client', this.addsale.get('id_client').value);

  }
  navigate() {
    this.saveData();
    this.router.navigate(['/prod']);
  }

}

Только клиент не показывает, все данные отображаются правильно.

Для client_id я пишу этоКод:

HTML-код:

    <form [formGroup]="addsale" (ngSubmit)="onaddsale()" class="col s12">
    <h4 style="text-align:center">add sale</h4>
    <div class="contant">
        <div class="row">
            <fieldset>
            <legend>Client Data</legend>
            <div class="input-field col s4">
            <mat-form-field class="example-full-width">
            <input formControlName="id_client" id="id_client" matInput placeholder="Select Client*" aria-label="State" [matAutocomplete]="auto"
                autoActiveFirstOption [formControl]="id_client">
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option (onSelectionChange)="updateClient($event, option.id_client, 'id_client')" *ngFor="let option of filteredOptions | async" [value]="option">
        {{option.name}}
       </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</div>
    </fieldset>
    <br>
      <div class="input-field col s4">
       invoice_number:
        <input formControlName="invoice_number" id="invoice_number" type="text" class="validate">
      </div>
      <div class="input-field col s4">
       description:
        <input formControlName="description" id="description" type="text" class="validate">
      </div>
    </div>
  </div>
  <br>    
  <button type="submit">
      Register sale
    </button>
    <br>
    <br>
</form>

Есть идеи, пожалуйста?Я должен сохранить все значения счета, такие как invoice_name и description.Спасибо!

Спасибо

ИЛЛЮСТРАЦИЯ ИЗОБРАЖЕНИЯ:

ШАГ 1: ИЗОБРАЖЕНИЕ ШАГ 2: ИЗОБРАЖЕНИЕ ШАГ 3: ИЗОБРАЖЕНИЕ

1 Ответ

0 голосов
/ 08 октября 2018

Вам необходимо указать имя атрибута в клиентском объекте, чтобы получить имя клиента

Вам нужно изменить в своем файле ts

 'id_client': new FormControl(id_client.name, Validators.required)

и в HTML

        <input formControlName="id_client" id="id_client" matInput placeholder="Select Client*" aria-label="State" [matAutocomplete]="auto"
            autoActiveFirstOption [formControl]="id_client.name">

Рабочая демоверсия https://stackblitz.com/edit/angular-9sijka-jo8bub?file=app/autocomplete-display-example.ts

...