javascriptangularangular6

How to receive data with parameter from Angular service


How to receive data from the service with parameters. I have 2 components and service. From one component I must to receive the data in the other component via the service. Look me code header.component.html

<li><a routerLink="contact-us">
  <select  (change)="onChange($event.target.value)">
    <option>CONTACT US</option>
      <option  *ngFor="let coun of countriesShow">{{ coun }} </option>
  </select>
</a>
</li>

header.component.ts

  onChange(data: string){
    this.countrySelect = this.ctry.onChange(data);
    return this.countrySelect;
  }

selectedcountry.service.ts

 public countrySelect: any;

 onChange(selectedCountry: string) {
    this.countrySelect = selectedCountry;
    return this.countrySelect;
}

     getCountry(){
      return this.countrySelect;
      }

contact-form.component.ts (this component must to recieve data from header and service)

public countrySelect: any;
constructor(private country: SelectedcountryService) { }


ngOnInit() {
   this.countrySelect = this.country.getCountry();
    console.log(this.countrySelect) // undefined
}

Solution

  • Your need to set an observable in your service for receiving the data when it changes.

    in selectedcountry.service.ts

     private countrySubject: BehaviorSubject<any> = new BehaviorSubject('');
     public country = this.countrySubject.asObservable();
    
     public setCountry(country: any) {
        this.countrySubject.next(country);
      }
    

    in header.component.ts

    constructor(private countryService: SelectedcountryService) { }
    onChange(selectedCountry: string) {
        this.countrySelect = selectedCountry;
        this.countryService.setCountry(this.countrySelect);
    }
    

    in contact-form.component.ts

    constructor(private countryService: SelectedcountryService) { }
    
    ngOnInit() {
       this.countryService.country.subscribe( (data) => {
        this.countrySelect = data;
        console.log(this.countrySelect);
       });
    }