如何在 Angular 5 中使用 ActivatedRoute? [英] How to use ActivatedRoute in Angular 5?

查看:25
本文介绍了如何在 Angular 5 中使用 ActivatedRoute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做与这篇文章完全相同的事情:Angular 4 get queryString

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

我使用的是 Angular 5.2.5.

I am using Angular 5.2.5.

ActivatedRoute 似乎是用来在用户第一次访问网站时从 URL 中检索查询字符串值的东西.但是,我无法弄清楚需要导入什么才能使用 ActivatedRoute.

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.

有人可以确切地指定需要添加到 app.module.ts 文件中的内容,以及我尝试使用 ActivatedRoute 的 component.ts 文件吗?

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?

这篇文章指定了向@NgModule 的导入数组添加路由:NoActivatedRoute 的提供者 - Angular 2 RC5.但是,我没有 app.routing.ts 文件.我是否必须创建 app.routing.ts 文件才能使用 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?

推荐答案

ActivatedRoute 包含有关与出口中加载的组件关联的路由的信息.它还可以用于将数据从一个组件传递到另一个组件,使用诸如Id、标志、状态等的路由

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 是您要编辑的测验的 id.

032 being id of the quiz you wanna edit.

在您的组件中获取此 ID(在我的情况下,让它成为 edit_quiz.compontent.ts)以使用 Activated Route.

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

步骤 1: 从路由器模块导入 ActivatedRoute.

Step 1: Import ActivatedRoute from Router module.

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

第 2 步: 在构造函数中注入 ActivatedRoute.

Step 2: Inject ActivatedRoute in constructor.

  constructor(private activatedRoute: ActivatedRoute) { }

第 3 步:ngOnInit(){}

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

现在我们在 edit_quiz.component.ts 中有 id 可以使用了.

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

这篇关于如何在 Angular 5 中使用 ActivatedRoute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆