javascript - 如何从 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
}
解决方案
您需要在服务中设置一个 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);
});
}
推荐阅读
- vba - 为什么错误处理程序触发时没有错误?
- docker - 如何使用 ENTRYPOINT 或 CMD 从 docker 进程捕获标准输出并通过管道传输到另一个进程
- javascript - 如何检查字符串中是否存在不区分大小写的子字符串?
- django - Django:安全删除旧迁移?
- java - 使用 JavaFX 获取当前记录的用户 ID 和用户名
- javascript - 节点 JS 不允许将 JSON 返回到 JSON 字符串中
- java - 未找到 com.google.protobuf.GeneratedMessageV3 的类文件
- python-3.x - pydub 没有找到 ffprobe
- git - How to tell the date time that a git branch is pushed to remote?
- javascript - DayJS 格式秒分钟和小时