Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ActivatedRoute in Angular 5?

I am trying to do exactly the same thing as in this post: Angular 4 get queryString

I am using Angular 5.2.5.

ActivatedRoute seems to be the thing to use to retrieve querystring values off the URL when the user first visits the website. However, I am unable to figure out what I need to import to be able to use ActivatedRoute.

Could someone specify exactly what needs to be added to the app.module.ts file, and the component.ts file where I am trying to use ActivatedRoute?

This post specifies adding routing to the imports array of the @NgModule: No provider for ActivatedRoute - Angular 2 RC5. However, I don't have an app.routing.ts file. Do I have to create an app.routing.ts file to use ActivatedRoute?

like image 203
Mark Nugent Avatar asked May 03 '18 22:05

Mark Nugent


Video Answer


1 Answers

ActivatedRoute Contains the information about a route associated with a component loaded in an outlet. It can also be used to pass data from one component to another component using route such as Id, flag, state etc.

http://localhost:4200/quiz/edit_quiz/032

032 being id of the quiz you wanna edit.

Get this id in your component(in my case let it be edit_quiz.compontent.ts) to use by using Activated Route.

Step 1: Import ActivatedRoute from Router module.

import { ActivatedRoute } from '@angular/router';

Step 2: Inject ActivatedRoute in constructor.

  constructor(private activatedRoute: ActivatedRoute) { }

Step 3: Get id on a local variable named quizId in ngOnInit(){}

   ngOnInit() {
    this.quiz_id = this.activatedRoute.snapshot.params['id'];
   }

Now we have id in edit_quiz.component.ts to use.

like image 54
Mr. Droid Avatar answered Oct 15 '22 21:10

Mr. Droid