简体   繁体   中英

Sending Variable from Component to Service in Angular 5

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.

"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 => { })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM