fdrk04
fdrk04

Reputation: 55

put request Angular to update entire object

I trying to do a put request to update a big object. The object is structured like this: Budget

The dailygoal with the date and the percentage is displayed like this

The user can change the percentage of the inputs and I need the put request to update the whole object once the user click on the "save" button.

my service.ts

export class UpdateDailyGoalService {
  constructor(
    private http: HttpClient,
    private StartDateService: StartDateService
  ) {}
  startDate = this.StartDateService.getStartDate();

  year = this.startDate.getFullYear();
  budget: Budget;

  putUrl = 'http://localhost:8080/budgets/{id}';
  getUrl = 'http://localhost:8080/budgets/search';

  getBudgetById(id): Observable<Budget> {
    const headers = new HttpHeaders().append('header', 'value');
    const params = new HttpParams().append('id', id);
    return this.http.get<Budget>(this.getUrl, { headers, params });
  }

  UpdateBudget(id): Observable<Budget> {
    const headers = new HttpHeaders().append('header', 'value');
    const params = new HttpParams().append('id', id);
    return this.http.put<Budget>(this.putUrl, { headers, params });
  }
}

my component.ts

//get budget by id
getBudgetById(id) {
  this.UpdateDailyGoalService.getBudgetById(id).subscribe((data) => {
    this.budget = data;
    console.log('data' + data);
  });
}

//put request dailygoals into
updateBudget(id) {
  // const data = JSON.stringify(this.budget.id);
  this.UpdateDailyGoalService.UpdateBudget(id).subscribe((data) => {
    this.budget.id = data.id;

    console.log('data id' + data.id);
  });
}

I don't know what s wrong with the functions but it doesn't work. I hope you can help me, thank you

Upvotes: 0

Views: 2717

Answers (1)

Piotr Sternik
Piotr Sternik

Reputation: 169

You must add the whole updated object to the PUT.

Service:

   UpdateBudget(id, updatedData): Observable<Budget> {
    const headers = new HttpHeaders().append('header', 'value');
    const params = new HttpParams().append('id', id);
    return this.http.put<Budget>(this.putUrl, updatedData, { headers, params });
  }

Component:

 //get budget by id
  getBudgetById(id) {
    this.UpdateDailyGoalService.getBudgetById(id).subscribe((data) => {
      this.budget = data;
      console.log('data' + data);
    });
  }

  updateBudget(id, updatedBudget) {
    this.UpdateDailyGoalService.UpdateBudget(id, updatedBudget).subscribe((data) => {
      this.budget.id = data.id;

      console.log('data id' + data.id);
    });
  }

Upvotes: 1

Related Questions