[英]Angular 8, How can I send the userinformation I recieve from a http call in a service with subscribe to another component?
[英]How to recieve data with parameter from Angular service
如何使用參數從服務接收數據。 我有 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
}
您需要在您的服務中設置一個 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);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.