C
C
Coder3212018-02-15 13:27:00
JavaScript
Coder321, 2018-02-15 13:27:00

How to check route path dynamically in Angular 5?

There is a date/:date type route in which date, respectively, must be a date like 12/20/2018. The first problem is that the router does not accept dots in the date and when the corresponding route is overloaded, it says "Cannot GET /date/12/20/2018"?, and the second is that I need to dynamically check whether this date is correct and if not, then replace it with correct, how to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitrygavrish, 2018-02-21
@dmitrygavrish

To get started, you can change the date format and use as a separator, for example, a hyphen (20-12-2018).
It is solved as follows:
1) in the component's constructor, private _activatedRoute: ActivatedRouteand private _router: Router
2) subscribe (preferably in ngOnInit) to ActivatedRoute and process the value of the route parameter:

this._activatedRoute.paramMap.subscribe((params: ParamMap) => {
    let date: string = params.get('date'); 

    if (/*если дата неправильна*/) {
      date = ...; // изменим дату на корректную
      this._router.navigate(['/date', date]);
    }
  })

If you need to validate a date using the native js Date constructor, please note that it will be valid to create a new Date('mm-dd-yyyy') object, i.e. new Date('20-12-2018') will return Invalid Date, because The 20th month does not exist.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question