Search code examples
angularservice

how to refactor some methods in a angular service?


I have a service with some methods that perform the same task with diferent variables.

updateImage1(token,id, image1):Observable<any>
  {
  
    let tokenid = JSON.stringify(token);
    let headers = new HttpHeaders().set('Content-Type','application/json')
    .set('Authorization', tokenid);


    return this.http.put(this.url + 'updateimage1',{'id':id, 'image1': image1}, {headers: headers});
  }
  updateImage2(id, image2):Observable<any>
  {
  
    let headers = new HttpHeaders().set('Content-Type','application/json');


    return this.http.put(this.url + 'updateimage1',{'id':id, 'image2': image2}, {headers: headers});
  }
 

How to know if the variable that the methods receive it is image1 or image2....


Solution

  • A simple refactor would be pass the property key you are replacing in the http call as a parameter to the method.

    updateImage(token, id, property, image):Observable<any>
    {
      let tokenid = JSON.stringify(token);
      let headers = new HttpHeaders().set('Content-Type','application/json').set('Authorization', tokenid);
    
      return this.http.put(this.url + 'updateimage1',{'id':id, [property]: image}, {headers: headers});
    }
    

    You would call as,

    updateImage(token, id, 'image1', image);
    updateImage(token, id, 'image2', image);