Sending Variable from Component to Service in Angular 5

…衆ロ難τιáo~ 提交于 2021-02-20 03:49:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!