Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
1
Indexable
Never
import { HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from "@angular/router";
import { exhaustMap } from 'rxjs';
import { ProgramPreferencesService } from '../services/program-preferences.service';

@Component({
  selector: 'app-program-preferences',
  templateUrl: './program-preferences.component.html',
  styleUrls: ['./program-preferences.component.css']
})
export class ProgramPreferencesComponent implements OnInit {
  PrefForm!: FormGroup;
  httpOptions: { headers: HttpHeaders };

  nodeId: number;
  isProgramLoaded = true;

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private ProgramPreferencesService:ProgramPreferencesService
  ) { }

  ngOnInit(): void {

    this.activatedRoute.params.subscribe((params) => {

      if (params["nodeId"]) {
        this.nodeId = +params["nodeId"];

      } else {
        this.isProgramLoaded = false;
      }
    });
  }

  // funkcija koja ce se pokrenuti kada se klikne Save 
  onSave() {
    // kupi sve iz forme i pretvara u JSON string
    var bodyString = this.stringifyProgram();

    //dohvata token (potrebno da bi se spojilo sa backendom, drupalom u ovom slucaju)
    this.ProgramPreferencesService.getToken()
      .pipe(
        exhaustMap((token: string) => {
          // dohvata headerse
          this.httpOptions = this.populateHeaders(token);
          //poziva service koji ce spremiti novi node u drupal sa content type program preferences
          return this.ProgramPreferencesService.createProgramPreferences(this.httpOptions, bodyString);
        })
      )
      .subscribe(() => {
        
      });
  }

  stringifyProgram() {
    // kupi sve iz forme za program preferences
    var body: any = JSON.stringify(this.PrefForm.value);
    let data = {
      // definise se kojeg ce content type biti novi node
      type: "program_preferences",
      title: [
        {
          value: "New preferences node",
        },
      ],
      // u Configuration sprema sve iz forme u JSON formatu kao string
      field_pref_configuration: [
        {
          value: body,
        },
      ],
      // sprema se programID u field Program reference 
      field_program_reference: [
        {
          value: this.nodeId,
        },
      ],
    };

    return JSON.stringify(data);
  }

  populateHeaders(token: string) {
    return {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        "X-CSRF-Token": token,
      }),
    };
  }

}