How to recieve 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....

问题:

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
}

回答1:

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);
   });
}
  • 发表于 2018-12-30 00:27
  • 阅读 ( 181 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除