带有查询参数的 router.navigate Angular 5 [英] router.navigate with query params Angular 5

查看:25
本文介绍了带有查询参数的 router.navigate Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在路由到带有查询参数的路由时遇到问题,我有一个类似这样的功能

I'm having an issue with routing to a route with query params I have a function like so

goToLink(link) {
    this.router.navigate([`${link.split('?')[0]}`, { queryParams: this.sortParams(link)}]);
}

还有这个功能

sortParams(link) {
    let queryParams = url.split('?')[1];
    let params = queryParams.split('&');
    let pair = null;
    let data = {};
    params.forEach((d) => {
      pair = d.split('=');
      data[`${pair[0]}`] = pair[1];
    });
    return data;
}

好吧,基本上发生了什么我有一个名为 goToLink() 的函数,它接受一个 url,传递的 url 是一个带有查询参数的字符串,就像这样..

okay so basically what Is happening I have a function called goToLink() and that takes in a url and the url that gets passed is a string with query params like so..

https://website.com/page?id=37&username=jimmy

上面只是一个例子,它不是它实际的样子,而是一个带有查询参数的链接字符串,所以我从字符串中删除参数并将它们存储在 sortParams() 函数,所以当我传递上面的字符串时,我得到一个看起来像这样的对象

the above is just an example thats not what it actually looks like but its a link string with query parameters now so what happens is I remove the params from the string and store them in a data object in the sortParams() function so when I pass the above string in I get an object that looks like this

{id: 37, username: 'jimmy'}

现在这就是我传递到 router.navigate 中的 queryParams: 部分的内容,

now thats what i'm passing into the queryParams: section in the router.navigate,

返回对象时函数应该是这样的

the function should look like this when the object is returned

this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]);

所以我成功地路由到所需的路由,但查询参数看起来像这样..

so i successfully route to the desired route but the query params look like this..

/page;queryParams=%5Bobject%20Object%5D

我在这里做错了吗??

任何帮助将不胜感激!

编辑

如果我只是把函数改成这个

If I just change the function to this

 this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]);

我得到相同的网址 /page;queryParams=%5Bobject%20Object%5D

推荐答案

可能是你已经放置了应该是第一个参数的括号,但你已经将它封装在整个路线上

Can be of that you had placed the bracket which is supposedly for the 1st param but you had encapsulated it on the whole line of route

您的代码:

// This is the end of your route statement:  '}}]);' which the close bracket is included
this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]);

更新路线:

仅将 ] 右括号放在第一个参数内,尽量不要将其放在路由语句的最后一部分.

place the ] close bracket within the 1st parameter only, try to not place it on the last part of the route statement.

// Update end line: '}});'
this.router.navigate([`${link.split('?')[0]}`], { queryParams: {id: 37, username: 'jimmy'}});


总结:

this.router.navigate([ url ], { queryParams: { ... } })

这篇关于带有查询参数的 router.navigate Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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