gpt4 book ai didi

javascript - 如何从 Angular 服务接收带参数的数据

转载 作者:行者123 更新时间:2023-11-29 20:47:11 25 4
gpt4 key购买 nike

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

最佳答案

您需要在您的服务中设置一个可观察对象,以便在数据发生变化时接收数据。

在 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);
});
}

关于javascript - 如何从 Angular 服务接收带参数的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53955869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com