在 Angular 5 中将变量从组件发送到服务 [英] Sending Variable from Component to Service in Angular 5
问题描述
在我当前的 Angular 5 项目中,我一直在通过我的服务成功调用 API
In my current Angular 5 project, I have been making successful API calls from my service
(代码保持简洁)
myService.ts :
myService.ts :
@Injectable()
export class my-service-service {
constructor(private _http: HttpClient) {
}
myData1() {
return this._http.get("API_URL")
.map(result => result);
}
并通过订阅上述服务访问有关我的连接组件的信息.
And accessing that information on my connected component by subscribing to the above service.
myComponent.ts:
myComponent.ts:
import { myServiceService } from './my-service-service.service';
@Component({
...
})
constructor(private router: Router,
private route: ActivatedRoute,
private _myData: myServiceService) {
...
}
ngOnInit() {
this._myData.myData1()
.subscribe(res => {
//Able to access data successfully here
}
}
现在我希望以相反的方向发送数据,从我的控制器到服务.例如假设我有
Now I wish to send a data in the opposite direction, from my controller to the service. For example suppose I have
public myVar: any;
并且我希望从我的服务访问这个变量(也许将它动态地附加到 API 调用中)我应该继续这样做吗.
And I wish to access this Variable from my service (maybe to append it to an API call dynamically) How about should I go on doing that.
推荐答案
以相反的方向发送数据,从我的控制器到服务"最好的方法是使用函数/方法参数.
"send a data in the opposite direction, from my controller to the service" the best way to do this is using function/method parameter.
//service.ts
myData1(parameter1) {
//do whatever you need with parameter1
return this._http.get("API_URL")
.map(result => result);
}
//component.ts
public myVar: any;
ngOnInit() {
this._myData.myData1(this.myVar).subscribe(res => { })
}
这篇关于在 Angular 5 中将变量从组件发送到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!