0

quiero realizar un update en un ion-select pero no lo consigo. Mi nivel de programación es muy bajo y todavía hay muchas cosas que no comprendo.

Las opciones las lee de una tabla ('categories') que tiene dos campos ('id', 'name') a través del método getAllCategories(), pero no consigo que se muestre el valor del campo 'name' que ya tiene asignado

Hago una búsqueda de la categoría con su correspondiente Id con el método getCategory(1)(he puesto un 1, porque no sé como buscar por medio de una variable) pero no me aparece seleccionado (donde pone 'Select Category') a pesar de que creo que estoy enviando bien el dato, porque aparece en el console.log

update-recipe.page.html

<ion-item lines="full">
    <ion-select id="category" name="category" placeHolder="Select Category" (ionChange)="ObtenerCategoryId($event)">
    <ion-select-option *ngFor="let category of categories" value="{{category.id}}">{{category.name}}</ion-select-option>
 </ion-select>
  </ion-item>
<form [formGroup]="updateRecipeForm" (ngSubmit)="onSubmit()" novalidate>
    <ion-item lines="full">
      <ion-label position="floating">Tittle</ion-label>
      <ion-input formControlName="tittle" type="text" required></ion-input>
    </ion-item>
    <!-- <span class="error ion-padding" *ngIf="isSubmitted && errorControl.name.errors?.required">Tittle is required.</span> -->
    <ion-item lines="full">
      <ion-label position="floating">Description</ion-label>
      <ion-input formControlName="description" type="text" required></ion-input>
    </ion-item>
      
    <!-- <span class="error ion-padding" *ngIf="isSubmitted && errorControl.description.errors?.required">Description is required.</span> -->
    <ion-row>
      <ion-col>
        <ion-button type="submit" color="primary" expand="block">Update</ion-button>
      </ion-col>
    </ion-row>
  </form>

update-recipe.page.ts

export class Recipe {
  id: number;
  tittle: string;
  description: string;
  filename: string;
  userId: number;
  categoryId: number;
}

@Component({
  selector: "app-update-recipe",
  templateUrl: "./update-recipe.page.html",
  styleUrls: ["./update-recipe.page.scss"],
})

export class UpdateRecipePage implements OnInit {

  categories: any =[];
  categoryId: any;
  updateRecipeForm: FormGroup;
  isSubmitted = false;
  id: any;
  capturedPhoto = '';
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
  imageSaved: string = '';

  constructor(
    private recipeService: RecipeService,
    private categoryService: CategoryService,
    private activatedRoute: ActivatedRoute,
    private formBuilder: FormBuilder,
    private router: Router,
    private photoService: PhotoService,
    private storage: Storage
  ) {
    this.id = this.activatedRoute.snapshot.paramMap.get('id');
  }

 ionViewWillEnter(){
    this.findRecipe(this.id);
    this.updateRecipeForm = this.formBuilder.group({
      tittle: [''],
      description: [''],
      filename: [''],
      categoryId: ['']
    });
    this.capturedPhoto = '';
    
  }  


  ngOnInit() {
    this.findRecipe(this.id);
    this.updateRecipeForm = this.formBuilder.group({
      tittle: [''],
      description: [''],
      filename: [''],
      categoryId: ['']
    },
    );
    this.capturedPhoto = '';
   //   this.updateRecipeForm.reset();
   this.getCategory(1);
   this.getAllCategories();
  }
 async findRecipe(id) {
    let token = await this.storage.get("token");
    this.recipeService.getRecipe(this.id, token).subscribe(async data => {
      this.imageSaved = data['filename'];
      this.updateRecipeForm.setValue({
        tittle: data['tittle'],
        description: data['description'],
        filename: data['filename'],
        categoryId: data ['categoryId']
      });
    });
    
  }

  async ObtenerCategoryId(e){
    console.log("valor obtenido"+e.detail.value);
    let categoryId = await this.storage.set("categoryId_st", e.detail.value);
  }

  async getCategory(id) {
    let token = await this.storage.get("token");
    
    this.categoryService.getCategory(id, token).subscribe(async res => {

      console.log(res);
      this.categories = res;
    }, error => {
      console.log(error);
      console.log("User not authenticated. Please log in");
      this.router.navigateByUrl("/home");
    });
  }

  async getAllCategories() {
    let token = await this.storage.get("token");
    
    this.categoryService.getCategories(token).subscribe(async res => {

      console.log(res);
      this.categories = res;
    }, error => {
      console.log(error);
      console.log("User not authenticated. Please log in");
      this.router.navigateByUrl("/home");
    });
  }
async onSubmit() {
    this.isSubmitted = true;
    if (!this.updateRecipeForm.valid) {
      return false;
    } else {
      let blob = null;
      if (this.capturedPhoto !== "") {
        const response = await fetch(this.capturedPhoto);
        blob = await response.blob();
      }
      (
      await this.recipeService
        .updateRecipe(this.id, this.updateRecipeForm.value, blob, this.getCategory(this.id)))
        .subscribe(data => {
          console.log('¡Photo sent!');
          this.updateRecipeForm.reset();
          this.router.navigate(['/you-are-logged-in']);
        });
    }
  }

Actualizando un ion-select

Lo que necesito es rescatar el valor de CategoryId de esta tabla(recipes): introducir la descripción de la imagen aquí

Y que lo lea de esta otra tabla(categories) y me lo muestre en la caja "Select Categories" introducir la descripción de la imagen aquí

1 respuesta 1

0

En la funcion getCategory estas asignando la variable this.categories a res el problema es que la variable this.categories es de tipo array y lo que te devuelve la funcion parece ser un objeto. En todo caso deberias hacer this.categories.push(res) para añadir el item al array. Y en el HTML deberia poner el value asi -->

<ion-select-option *ngFor="let category of categories" [value]="category">{{category.name}}</ion-select-option>
3
  • Gracias pero sigue sin funcionar. No me aparece el valor "categoryId" que tengo en la base de datos. Que podrá ser??
    – octavio67
    el 29 ene. a las 13:00
  • He ampliado la pregunta
    – octavio67
    el 29 ene. a las 13:20
  • Puedes añadir el atributo [(ngModel)]="myId" ---> <ion-select [(ngModel)]="myId"> Y luego declarar la variable myId en update-recipe.page.ts ---> myId: any = '' Luego modificar [value]="category" por [value]="category.id" el 30 ene. a las 1:30

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.