Search code examples
angularrestangular-services

Angular 2 pass value to service


I know how to pass data to and from a nested component. But I have a service that gets some data from a REST API. I need the URL in my service to change when I click and run a function. I need to pass an ID to my service and change my URL.

I my component:

showUnitDetails(selectedUnit) {
    this.unitId = selectedUnit;
    this.unitDetails = true;
    this._unitService.getUnit(this.unitId).subscribe(resUnitData => this.unit = resUnitData, err => alert('Error'));
}

In my Service:

getUnit(id: unitId){
    return this._http.get(this._url).map((response: Response) => response.json());
}

But when i save my service I get the error "Cannot find name unitId".


Solution

  • I made you a quick example showing how to hook up a component and http service together with parameters where you can pass in the id and url.

    Module:

    import { NgModule } from "@angular/core"
    
    //A Module
    @NgModule({
      declarations: [MyComponent],
      providers: [MyService],
    })
    export class MyModule {}
    

    Component:

    import { Component } from "@angular/core"
    import { MyService } from 'path-to-service';
    
    //The Component
    @Component({
      selector: 'my-component',
      templateUrl: './my-component.component.html',
    })
    
    export class MyComponent {
      private id: number;
      private url: string;
    
      constructor(public myService: MyService) {}
    
      ngOnInit() {
        this.id = 123;
        this.url = '/api/stuff';
    
        this.myService
          .getStuff(this.id, this.url)
          .subscribe(response => {
              console.log(response);
            },
            error => {
              console.log(error);
            })
      }
    }
    

    Service:

    import { Injectable } from '@angular/core';
    import { Http } from "@angular/http"
    
    //The Service
    @Injectable()
    export class MyService {
      constructor(private http: Http) {}
    
      getStuff(id: number, url: string) {
        const urlWithId = url + id;
    
        return this.http
          .get(urlWithId)
          .map(res => res.json())
      }
    }