问题
In my current Angular 5 project, I have been making successful API calls from my service
(Code kept clean for brevity)
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:
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;
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.
回答1:
"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 => { })
}
来源:https://stackoverflow.com/questions/50297742/sending-variable-from-component-to-service-in-angular-5