Home > Software engineering >  Angular: Method for accessing queryParams in ngOnInit is not working, when calling a routing method
Angular: Method for accessing queryParams in ngOnInit is not working, when calling a routing method

Time:09-27

I am currently learning Angular Routing and got this error. So here in coursecomponent, i was try to modify the web content using queryParam and variable editMode:boolean - its default value is false.

Stackblitz code link

https://github-jrdc2r.stackblitz.io/Course/101?edit=true

course.component.ts

export class CourseComponent implements OnInit, OnDestroy {

  constructor(private service: CoursesService, private route: ActivatedRoute, private router: Router) { }

  course: any;
  courseId: any;
  routeParamObservable: any;
  queryParamObservable: any;
  editMode: boolean = false;

  addOueryParam() {
    this.router.navigate(['/Course', this.courseId], { queryParams: { edit: true } });
  }

  //saveUpdateNameChange() {
    //this.router.navigate(['/Course', this.courseId]);
  //}

  // --------------------------ERROR is here----------------------------------
  //Route working but accessing query-params using observables is not working
   saveUpdateNameChange() {
     this.router.navigate(['/Course', this.courseId], { queryParams: { edit: false } });
   }

  ngOnInit(): void {
    // this.courseId = this.route.snapshot.params['id'];
    // this.courseId = this.route.snapshot.paramMap.get('id');
    // this.course = this.service.courses.find(x => x.id == this.courseId);

    this.routeParamObservable = this.route.paramMap.subscribe({
      next: (param) => {
        this.courseId = param.get('id');
        this.course = this.service.courses.find(x => x.id == this.courseId);
      }
    })

    //when manually refresh the page
    this.router.navigate(['/Course', this.courseId]);

    //accessing query-parms using snapshot //! This doesn't work
    // this.editMode = Boolean(this.route.snapshot.queryParamMap.get('edit'));

    //accessing query-parms using observables 
    this.queryParamObservable = this.route.queryParamMap.subscribe({
      next: (param) => {
        this.editMode = Boolean(param.get('edit'));
        console.log(this.editMode);
      }
    })
  }

  ngOnDestroy(): void {
    this.routeParamObservable.unsubscribe();
    this.queryParamObservable.unsubscribe();
  }

}

course.component.html

<div >
    <div>
        <img src="{{course.image}}" width="560" height="280">
    </div>
    <div>
        <h1 *ngIf="!editMode" style="text-align: center;">{{course.name}}</h1>
        <div *ngIf="editMode" style="text-align: center;">
            <input type="text" [(ngModel)]="course.name">
        </div>
    </div>
    <div >
        <div style="margin: 0px 10px;"><b>Author: </b>{{course.author}}</div>
        <div style="margin: 0px 10px;"><b>Duration: </b>{{course.duration}}</div>
        <div style="margin: 0px 10px;"><b>Type: </b>{{course.type}}</div>
    </div>
    <div style="margin: 0px 10px;">
        <h2>Price: {{course.price}}$</h2>
    </div>
    <div style="margin: 20px 10px;">
        <p>{{course.description}}</p>
    </div>

    <button (click)="addOueryParam()" *ngIf="!editMode">Edit</button>
    <button (click)="saveUpdateNameChange()" *ngIf="editMode">Save Update</button>
</div>

So here, after calling addOueryParam() method .

  • when i am trying to save the change by calling saveUpdateNameChange() {this.router.navigate(['/Course', this.courseId], { queryParams: { edit: false } });} - method with queryParams => routing is working but method for accesing queryParams in ngOnInit is not working and console log is not showing false.
  • While when calling saveUpdateNameChange() {this.router.navigate(['/Course', this.courseId]);} - method without queryParams => routing and method for accesing queryParams in ngOnInit is working completely fine and can see the console log is showing false.

So how method for accesing queryParams in ngOnInit is working when calling method without queryParams and its not working when calling a method with queryParams for this specific case ?

PS: Please forgive if my question is wrong.

CodePudding user response:

false is also getting logged in the console. I just checked https://github-jrdc2r.stackblitz.io/Course/101

Seems like issue is with your conversion into boolean. Boolean always returning true in case of false also.

Replace code inside of queryparamMap with below

    console.log(param.get('edit'));
    var d = param.get('edit') || '';
    this.editMode = JSON.parse(d);
    console.log(this.editMode);

Point is try JSON.parse for your boolean conversion.

  • Related