1

when i try to navigate from the item page list to the single item view , i have this error : The requested path contains undefined segment at index 1

The code of my service

import { Injectable } from '@angular/core';
import * as firebase from 'firebase';
import { Prospect } from '../models/Prospect.model';
import { Subject } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class ProspectsService {

  prospects : Prospect[] = [];
  prospectsSubject = new Subject<Prospect[]>();

  constructor() { }

  emitProspects() {
    this.prospectsSubject. next(this.prospects);
  }

  saveProspects() {
    firebase.database().ref('/prospects').set(this.prospects);
  }

  createProspect(newProspect : Prospect)
{
  this.prospects.push(newProspect);
  this.saveProspects();
  this.emitProspects();
}

removeProspect(prospect : Prospect) {
  const  index = this.prospects.findIndex(
   (prospectEl) => {
     if(prospectEl === prospect) {
       return true;
     }
   }
 );
 this.prospects.splice(index, 1);
 this.saveProspects();
 this.emitProspects();
 }
getProspects()
{firebase.database().ref('/prospects').on('value',(data) => {
  this.prospects=data.val() ? data.val() : [];
  this.emitProspects();
});}

updateProspect(prospect: Prospect, id: number){
  firebase.database().ref('/prospects/' + id).update(prospect);
}
getSingleProspect(id: number) {
  return new Promise(
    (resolve, reject) => {
      firebase.database().ref('/prospects/' + id).once('value').then(
        (data) => {
          resolve(data.val());
        },
        (error) => {
          reject(error);
        }
      );
    }
  );
}
}

The code of my principal component is :

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import * as $ from 'jquery'
import { ProspectsService } from 'src/app/services/prospects.service';
import { Prospect } from 'src/app/models/Prospect.model';
import { Subscription } from 'rxjs';
import { Router } from '@angular/router';

@Component({
  selector: 'app-admin-prospects',
  templateUrl: './admin-prospects.component.html',
  styleUrls: ['./admin-prospects.component.css']
})
export class AdminProspectsComponent implements OnInit , OnDestroy{

  prospectForm: FormGroup;
  prospectsSubscription: Subscription;
  prospects : Prospect[];
  editProspect: boolean = false;

  constructor(private formBuilder: FormBuilder , 
     private prospectsService: ProspectsService ,
     private router: Router) { }

  ngOnInit() {
    this.initform();
    this.prospectsSubscription = this.prospectsService.prospectsSubject.subscribe(
      (prospects: Prospect[]) =>{
        this.prospects = prospects;
      }
    );
    this.prospectsService.getProspects();
    this.prospectsService.emitProspects();

  }
  initform(){

    this.prospectForm = this.formBuilder.group({
      id: [''], 
      nom: ['' , Validators.required],
      entreprise: ['' , Validators.required],
      mail: ['' , Validators.required],
      phone: ['' , Validators.required],
      description: ['']
    });

    }
    resetProspectForm(){
      this.editProspect = false;
      this.prospectForm.reset();
    }
    onSaveProspect(){
      const id = this.prospectForm.get('id').value;
      const nom = this.prospectForm.get('nom').value;
      const entreprise = this.prospectForm.get('entreprise').value;
      const mail = this.prospectForm.get('mail').value;
      const phone= this.prospectForm.get('phone').value;
      const description = this.prospectForm.get('description').value;
      const newProspect = new Prospect(nom, entreprise , mail , phone , description); 
     if(this.editProspect == true)
     {
       this.prospectsService.updateProspect(newProspect, id);

     }
     else{
       this.prospectsService.createProspect(newProspect);
     }



      $('#prospectsFormModal').modal('hide');
      this.prospectForm.reset();
    }
    ngOnDestroy(){
      this.prospectsSubscription.unsubscribe();
    }
    onDeleteProspect(prospect : Prospect) {
      this.prospectsService.removeProspect(prospect);
    }

    onEditProspect(prospect: Prospect , id:number){
   $('#prospectsFormModal').modal('show');
   this.prospectForm.get('id').setValue(id);
   this.prospectForm.get('nom').setValue(prospect.nom);
   this.prospectForm.get('entreprise').setValue(prospect.entreprise);
   this.prospectForm.get('mail').setValue(prospect.mail);
   this.prospectForm.get('phone').setValue(prospect.phone);
   this.prospectForm.get('description').setValue(prospect.description);
   this.editProspect = true;

 }
 onViewProspect(id:number) 
 {
    this.router.navigate(['/prospect' , id]);  

 }


  }

and the html code :

        <div class="row">
            <div class="col-12 d-flex">
                <h2 class="font-weight-light"><i class="fas fa-user"></i> Prospect</h2>
                 <button class="btn btn-primary ml-auto" type="button" data-toggle="modal" data-target="#prospectsFormModal"><i class="fas fa-plus"></i> Ajouter un prospect</button>
        </div>
        </div>
        <hr class="mt-1 mb-5 bg-dark">
        <div class="row">
            <div *ngFor="let prospect of prospects" class="col-12 shadow-sm p-4 mb-3 bg-light">
                <div class="row">
                    <h3 class="font-weight-normal pl-3">{{ prospect.nom }}</h3>

                    <div class="ml-auto">
                            <div class="ml-auto">
         <button class="btn btn-primary my-3 mx-auto"(click)="onViewProspect(i)">Plus de détails</button>
            <button class="btn btn-primary m-1"(click)="onEditProspect(prospect,i)"><i class="fas fa-edit"></i></button>
            <button class="btn btn-danger m-1"(click)="onDeleteProspect(prospect)"><i class="fas fa-trash-alt"></i></button>
                    </div>
                </div>
                <p>de {{ prospect.entreprise}}</p>
            </div>
                </div>
            </div>


    <div class="modal fade" id="prospectsFormModal" tabindex="-1" role="dialog" aria-labelledby="exampleModal3Label" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="rounded shadow bg-white p-5">
                    <h3 class="font-weight-light">Nouveau Prospect</h3>
                    <hr class="mt-0 bg-dark">
                    <form [formGroup]="prospectForm" class="py-5" (ngSubmit)="onSaveProspect()">
                        <div class="form-group">
                            <input type="text" formControlName="nom" id="nom" placeholder="Nom" class="form-control">
                        </div>
                        <div class="form-group">
                                <input type="text" formControlName="entreprise" id="entreprise" placeholder="Entreprise" class="form-control">
                            </div>
                            <div class="form-group">
                                    <input type="email" formControlName="mail" id="mail" placeholder="Adresse Email" class="form-control">
                                </div>
                                <div class="form-group">
                                        <input type="tel" formControlName="phone" id="phone" placeholder="Numéro de Téléphone" class="form-control">
                                    </div>
                                    <div class="form-group">
                                            <textarea class="form-control" formControlName="description" id="description" placeholder="Description"></textarea>

                                        </div>
                                        <button class="btn btn-primary float-right" type="submit" [disabled]="prospectForm.invalid">Enregistrer</button>
                                    </form>

                </div>
            </div>
        </div>
    </div>

This problem appears only when i try to navigate to a single view with " onViewProspect"

Thank you for helping me

Rajat
  • 398
  • 1
  • 5
  • 16
Silma
  • 13
  • 1
  • 4
  • well, what is `i` that you are passing to the function? Looks like `undefined` to me, like error also tells you. If you are new to coding, I suggest to learn how to debug your code. It can for example be done with console logging a lot to find what values are present and (sometimes) which values that are not :) Also important to carefully read the error messages, they are there for a reason, to tell you what is wrong :) – AT82 Sep 21 '19 at 18:36
  • Please check https://stackoverflow.com/a/48149365/9880356 – Giannis Dec 16 '20 at 14:43

2 Answers2

3

Probably your id that pass into in navigate is undefined or null. console your id and fix and then pass into in navigate. I had the same issue and fixed it.

Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
0

the only one solution that i broke my head searching it and find it in the end by myself : is that, you must name your attribute class in angular, the same way you named the attributes coming from your back (rest api). that means if you will get { "userId":1, "name":"xx" } object from your rest api, you must name your class attributes in angular the same way, example:

class User{ userId!: number, name!: string }

finally, the code will run without crushing your brain <button (click)= 'updateUser(user.userId)' class="btn btn-info"> Update

ol_fsd
  • 1
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 05 '22 at 09:38