angular 参数映射_如何在Angular中使用查询参数

news/2024/7/4 9:42:21

angular 参数映射

介绍 (Introduction)

Query parameters in Angular allow for passing optional parameters across any route in the application. Query parameters are different from regular route parameters, which are only available on one route and are not optional (e.g., /product/:id).

Angular中的查询参数允许跨应用程序中的任何路由传递可选参数。 查询参数与常规路由参数不同,后者仅在一条路由上可用,并且不是可选的(例如/product/:id )。

In this article, we will reference an example of an application that displays a list of products. We will provide optional order and price-range values that the receiving component can read and act on. The values provided will affect the ordering and filtering of the list of products.

在本文中,我们将引用一个显示产品列表的应用程序示例。 我们将提供可选的orderprice-range值,接收组件可以读取并对其执行操作。 提供的值将影响产品列表的排序和过滤。

Router.navigate使用查询参数 (Using Query Parameters with Router.navigate)

If you are navigating to the route imperatively using Router.navigate, you will pass in query parameters with queryParams.

如果您导航到使用势在必行路线Router.navigate ,你将通过与查询参数queryParams

In our example, if we want to route visitors to the products with the list ordered by popularity, it would look like this:

在我们的示例中,如果我们想将访问者引导至具有按受欢迎程度排序的列表的产品,则外观如下所示:

goProducts() {
  this.router.navigate(['/products'], { queryParams: { order: 'popular' } });
}

This will result in a URL that looks like this:

这将导致URL如下所示:

http://localhost:4200/products?order=popular

You can also provide multiple query parameters. In our example, if we want to route visitors to the products with the list ordered by popularity and filtered with an expensive price range, it would look like this:

您还可以提供多个查询参数。 在我们的示例中,如果我们想将访问者引导至具有按受欢迎程度排序的列表并以昂贵的价格范围进行过滤的产品,则外观如下所示:

goProducts() {
  this.router.navigate(['/products'], { queryParams: { order: 'popular', 'price-range': 'not-cheap' } });
}

This will result in a URL that looks like this:

这将导致如下所示的URL:

http://localhost:4200/products?order=popular&price-range=not-cheap

Now, you have an understanding of how queryParams can be used to set query parameters.

现在,您已经了解如何使用queryParams设置查询参数。

使用queryParamsHandling保留或合并查询参数 (Preserving or Merging Query Parameters with queryParamsHandling)

By default, the query parameters are lost on any subsequent navigation action. To prevent this, you can set queryParamsHandling to either 'preserve' or 'merge'.

默认情况下,查询参数在任何后续导航操作中都会丢失。 为了防止这种情况,您可以将queryParamsHandling设置为'preserve''merge'

In our example, if we want to route visitors from a page with the query parameter { order: 'popular' } to the /users page while keeping the query parameters, we would use 'preserve':

在我们的示例中,如果我们希望将访问者从具有查询参数{ order: 'popular' }的页面路由到/users页面,同时保留查询参数,则可以使用'preserve'

goUsers() {
  this.router.navigate(['/users'], { queryParamsHandling: 'preserve' });
}

This will result in a URL that looks like this:

这将导致如下所示的URL:

http://localhost:4200/users?order=popular

In our example, if we want to route visitors from a page with the query parameter { order: 'popular' } to the /users page while passing the query parameter { filter: 'new' }, we would use 'merge':

在我们的示例中,如果要将访问者从具有查询参数{ order: 'popular' }的页面路由到/users页面,同时传递查询参数{ filter: 'new' } ,则可以使用'merge'

goUsers() {
  this.router.navigate(['/users'], { queryParams: { filter: 'new' }, queryParamsHandling: 'merge' });
}

This will result in a URL that looks like this:

这将导致URL如下所示:

http://localhost:4200/users?order=popular&filter=new

Note: Preserving query parameters used to be done with preserveQueryParams set to true, but this is now deprecated in Angular 4+ in favor of queryParamsHandling.

注:保留用于查询参数与做preserveQueryParams设置为true ,但现在已经过时,在角4+赞成queryParamsHandling

Now, you have an understanding of how queryParamsHandling can be used to preserve and merge query parameters.

现在,您已经了解如何使用queryParamsHandling保留和合并查询参数。

In our example, if instead you are using the RouterLink directive to navigate to the route, you would use queryParams like this:

在我们的示例中,如果改为使用RouterLink指令导航到路由,则可以使用queryParams

<a [routerLink]="['/products']" [queryParams]="{ order: 'popular'}">
  Products
</a>

And in our example, if you want to 'preserve' or 'merge' query parameters on subsequent navigation you would use queryParamsHandling like this:

在我们的示例中,如果要在后续导航中'preserve''merge'查询参数,可以使用queryParamsHandling如下所示:

<a [routerLink]="['/users']"
   [queryParams]="{ filter: 'new' }"
   queryParamsHandling="merge">
  Users
</a>

Now you understand how queryParams and queryParamsHandling can be used with RouterLink.

现在,您了解如何将queryParamsqueryParamsHandlingRouterLink一起使用。

访问查询参数值 (Accessing Query Parameter Values)

Now that we know how to pass in optional query parameters to a route, let’s see how to access these values on the resulting routes. The ActivatedRoute class has a queryParams property that returns an observable of the query parameters that are available in the current URL.

现在,我们知道了如何将可选的查询参数传递给路由,让我们看看如何在生成的路由上访问这些值。 ActivatedRoute类具有queryParams属性,该属性返回可观察到的当前URL中可用的查询参数。

Given the following route URL:

给定以下路线URL:

http://localhost:4200/products?order=popular

We can access the order query parameter like this:

我们可以这样访问order查询参数:

// ...
import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/filter';@Component({ ... })
export class ProductComponent implements OnInit {
  order: string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.queryParams
      .filter(params => params.order)
      .subscribe(params => {
        console.log(params); // { order: "popular" }

        this.order = params.order;
        console.log(this.order); // popular
      }
    );
  }
}

In the console log, we would see the params object:

在控制台日志中,我们将看到params对象:


   
Output
{ order: "popular" }

And the params.order value:

params.order值:


   
Output
popular

There’s also queryParamMap, which returns an observable with a paramMap object.

还有queryParamMap ,它返回一个带paramMap对象的可观察对象。

Given the following route URL:

给定以下路线网址:

http://localhost:4200/products?order=popular&filter=new

We can access the query parameters like this:

我们可以像这样访问查询参数:

this.route.queryParamMap
  .subscribe((params) => {
    this.orderObj = { ...params.keys, ...params };
  }
);

We used the object spread operator here, and this is the resulting shape of the data in orderObj:

我们在这里使用了对象散布运算符 ,这是orderObj数据的最终形状:

{
  "0": "order",
  "1": "filter",
  "params": {
    "order": "popular",
    "filter": "new"
  }
}

Now, you have an understanding of how queryParams and queryParamMap can be used to access values on the resulting routes.

现在,您已经了解如何使用queryParamsqueryParamMap访问结果路由上的值。

结论 (Conclusion)

In this article, you used different examples to set and get query parameters in Angular. You were introduced to queryParams and queryParamsHandling with Router.navigate and RouterLink. You were also introduced to queryParams and queryParamMap with ActivatedRoute.

在本文中,您使用了不同的示例来设置和获取Angular中的查询参数。 向您介绍了queryParamsqueryParamsHandlingRouter.navigateRouterLink 。 还向您介绍了ActivatedRoute queryParamsqueryParamMap

If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.

如果您想了解有关Angular的更多信息,请查看我们的Angular主题页面,以获取练习和编程项目。

翻译自: https://www.digitalocean.com/community/tutorials/angular-query-parameters

angular 参数映射


http://www.niftyadmin.cn/n/3647808.html

相关文章

html 属性中使用变量_如何使用HTML属性

html 属性中使用变量How To Build a Website With HTML 如何使用HTML构建网站This tutorial series will guide you through creating and further customizing this website using HTML, the standard markup language used to display documents in a web browser. No prior …

CamGameSDK 摄像头游戏SDK提供测试版本。欢迎使用

目前CamGameSDK已经能完成类似CamGoo这个游戏中用到的摄像头图象识别技术。&#xff08;不知道什么是摄像头游戏的&#xff0c;请下载CamGoo这个游戏&#xff09;。现在整理出SDK一个。提供大家注册使用。如果有需要请与我联系。申请者填写如下表格一张发到我邮箱:xheartblue16…

如何嵌套HTML元素

How To Build a Website With HTML 如何使用HTML构建网站This tutorial series will guide you through creating and further customizing this website using HTML, the standard markup language used to display documents in a web browser. No prior coding experience i…

高效率视频播放: GPU支持的YUV RGB 转化例子(2)

最近一直在做视频的播放。尤其是HD的视频&#xff0c;即使是1024 x 576的视频播放在CPU消耗上是一个巨大的压力。更大的还有1920 x 1080的。在CPU的消耗上简直就是一个恶梦。 最近用DSHOW做了一个Demo。一般Dshow的例子里都是直接用VMR把视频播放出去。对于游戏开发人员跟视…

如何在React Native中将路由与React导航一起使用

介绍 (Introduction) React Navigation is a popular library for routing and navigation in a React Native application. React Navigation是一个流行的库&#xff0c;用于在React Native应用程序中进行路由和导航。 This library helps solve the problem of navigating b…

线程的优先级

这两天在用 mpg123改一个mp3的播放器。解码过程显然是要放到一个线程里的&#xff0c;于是改完mpg123的main函数后&#xff0c;就把它放到一个新启动的线程里去&#xff0c;主函数这么写的int main(){ MP3Lib_open("test.mp3"); MP3Lib_play(); While(…

css3失去焦点伪类_CSS:伪类内的焦点

css3失去焦点伪类介绍 (Introduction) Selecting a parent element has long been impossible to do using just CSS, but a pseudo-class, :focus-within, changes that story somewhat. It allows to style an element when it has focus, but also when any of its inner el…

绘制恒线速度的参数曲线

假设一条参数曲线和某个参数 t 相关。L: x f(t) y g(t)如果我们绘制这条参数曲线的时候的&#xff0c;t是按比例增加的话。可能点的分布会不均匀。那么按照什么公式来决定t的步长能让曲线的点分布均匀呢&#xff1f;首先我们对参数曲线公式进行微分。dx df(t)dy dg…