Angular的get传递多参数问题

本文介绍Angular5中HttpClient模块的使用技巧,特别是如何通过HTTP请求传递复杂参数。演示了一种将自定义对象转换为JSON格式的方法,以便于作为查询字符串进行传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

楼主在自学Angular5的时候发现,新版的Angular已经丢弃http的形式改用Httpclient。但是在demo中发送http.get请求并传递多参数的时候发现,参数params如果是HttpParams类型的话,只能传递单参数,传递多参数要么被覆盖要么无法传递(不清楚是我自己代码问题还是啥),后面查看client.ds.ts中对params的声明,发现params除了可以传递HttpParams外,还可以直接传递JSON或者string类型。所以,楼主就自己简单了写了一个实现JSON传输的方法,可支持单复参数。

export class ProductSearchParames {
  constructor(
    public title: string,
    public price: number,
    public category: string
  ) {
  }
}
  public encodeParams(params: ProductSearchParames) {
    return Object.keys(params)
      .filter(key => params[key])
      .reduce((json: any, key: string) => {
        json[key] = params[key];
        return json;
      }, []);
  }

  search(params: ProductSearchParames): Observable<any> {
    return this.http.get('/api/products', {params: this.encodeParams(params)});
  }
在本地测试,可以正常传输参数,并且后台亦可正常接收

可以使用 Angular 的路由参数来传递参数。在定义路由时,可以使用 `path` 属性来指定路由路径,并使用 `:parameter` 的格式来定义参数。例如: ```typescript const routes: Routes = [ { path: 'user/:id', component: UserComponent } ]; ``` 在上面的例子中,`:id` 表示一个参数,它可以是任何字符串,并且出现在 `user` 路径的末尾。要传递参数,可以使用 `navigateByUrl` 方法并将参数作为对象传递。例如: ```typescript this.router.navigateByUrl('/user/' + userId); ``` 在上面的例子中,`userId` 是一个变量,它包含要传递的参数。如果有多个参数,则可以将它们作为对象传递,如下所示: ```typescript this.router.navigateByUrl('/user/' + userId + '?name=' + userName); ``` 在上面的例子中,`userName` 是另一个参数,它使用查询字符串的方式传递。在组件中,可以使用 `ActivatedRoute` 服务来获取参数。例如: ```typescript import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { userId: string; userName: string; constructor(private route: ActivatedRoute) { } ngOnInit(): void { this.route.paramMap.subscribe(params => { this.userId = params.get('id'); this.userName = params.get('name'); }); } } ``` 在上面的例子中,`ActivatedRoute` 服务提供了 `paramMap` 属性,它是一个可观察对象,可以订阅以获取参数值。在 `ngOnInit` 生命周期钩子中,订阅了 `paramMap` 属性,并使用 `get` 方法获取参数值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值