0

I have two components, where the second changes according to the name selected in the first component.

If I select 'Bryan' in the first component my service should fetch the information regarding Bryan in the database and move to my second component since it has the function of generating the table with the information.

I tried to use the Subject class, but could not associate the emit with the return of the HTTP request that is observable.

template

<form class="mt-4" [formGroup]="managerForm">
  <ng-container *ngFor="let teamSale of teamSales">
    <label for="ManagerName" class="mt-2">{{ teamSale }}</label>
    <select id="ManagerName" class="form-control form-control-sm" formControlName="ManagerName" (change)="getAccountsByName()">
      <ng-container *ngFor="let manager of managers">
        <option *ngIf="manager.Team === teamSale" [value]="manager.Name">{{ manager.Name }}</option>
      </ng-container>
    </select>
    <hr>
  </ng-container>
</form>

enter image description here

service

import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';

import { Account } from 'src/app/models/account-model';

@Injectable({ providedIn: 'root' })
export class QuotationService {

    private urlAPI: string = 'http://localhost:9095';

    private quotationByManegerSource = new Subject<Account[]>();
    public quotationByManeger$ = this.quotationByManegerSource.asObservable();

    constructor(private http: HttpClient) { }

    public getAccountsByName(managerName: string): Observable<Account[]> {
        const url: string = `${this.urlAPI}/get-accounts-by-name/${managerName}`
        return this.http.get<Account[]>(url)
    }
}

I want, when selecting a name, the information in the database that refers to that name is passed to another component.

And let this second component listen to the changes made in the first component.

Leonardo Vinicius
  • 213
  • 1
  • 2
  • 8
  • Here is an example that has a stackblitz demo https://stackoverflow.com/questions/55317878/how-to-set-or-pass-a-property-state-between-unnested-component-in-angular/55318104#55318104 – Jason White Apr 15 '19 at 18:47

1 Answers1

1

You can create a subject inside your service

messageSource: Subject<string>; and instantiate inside your constructor

this.messageSource = new Subject<string>();

in your component you can do this,

this.yourService.messageSource.next('whatvermessage');

and if you want to subscribe to it, you can do

this.yourService.messageSource.asObservable().subscribe((value: string) => {

});
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396