如何使用Angular服务中的参数接收数据

时间:2018-12-28 08:54:19

标签: javascript angular angular6

如何使用参数从服务接收数据。我有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
}

1 个答案:

答案 0 :(得分:2)

您需要在服务中设置一个可观察对象,以便在数据更改时接收数据。

在selectedcountry.service.ts

fwrite

在header.component.ts

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

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

在contact-form.component.ts

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