首页 > 解决方案 > 如何从 Angular 服务接收带有参数的数据

问题描述

如何使用参数从服务接收数据。我有 2 个组件和服务。我必须从一个组件通过服务接收另一个组件中的数据。看我代码 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(该组件必须从标头和服务中接收数据)

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


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

标签: javascriptangularangular6

解决方案


您需要在服务中设置一个 observable,以便在数据更改时接收数据。

在 selectedcountry.service.ts

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

 public setCountry(country: any) {
    this.countrySubject.next(country);
  }

在 header.component.ts

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

在contact-form.component.ts

constructor(private countryService: SelectedcountryService) { }

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

推荐阅读