【问题标题】:Extract URL Query Parameters from Request URL in Angular 8从 Angular 8 中的请求 URL 中提取 URL 查询参数
【发布时间】:2020-04-17 09:38:05
【问题描述】:

有什么方法可以从我的 Angular 服务中的任何特定 URL 获取 GET URL 查询字符串参数?

例如假设我有一个 URL = "http:localhost/?id=123&name=abc"; 或 URL = "http://www.myexamplewebsite.com?id=123&name=abc";

// in my service.ts
public myFunction(): Observale<any>
{
 let getVariable= this.http.get(URL);
 return getVariable.pipe(map(response => <Object>response), catchError(error => this.handleError(error)));
}

那么在我的 component.tsservice.ts 中,有什么方法可以提取此 ID 和名称吗?我是这个话题的新手。

注意:我没有在我的路由中运行该 URL。所以 this.route.snap.params 函数没有帮助。

【问题讨论】:

  • 你有没有在这段代码中使用过角度路由器?

标签: javascript node.js angular typescript


【解决方案1】:

尝试使用 Angular 的 HttpParams。导入这个:import { HttpClient,HttpParams } from '@angular/common/http'; 并使用get(paramName)getAll()as String[]。

这是另一个获取参数的示例:https://www.tektutorialshub.com/angular/angular-pass-url-parameters-query-strings/

【讨论】:

    【解决方案2】:

    可以通过在组件构造函数中注入Activatedroute来获取参数:

    constructor(activatedRoute: ActivatedRoute) {
        let id = activatedRoute.snapshot.queryParams['id'];
        let name = activatedRoute.snapshot.queryParams['name'];
    }
    

    【讨论】:

      【解决方案3】:

      在你的组件中这样做。

      导入它。

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

      然后在构造函数中

      private route: ActivatedRoute,
      

      然后你可以得到这样的参数。

      this.route.queryParams.subscribe(data => {
          console.log(data)
      });
      

      working demo

      试试这个url 并检查控制台。您将获得查询参数。

      如果您仍有问题,请告诉我。

      您也可以查看此网址 - https://angular-routing-query-params.stackblitz.io/?abc=test&xyz=test2

      输出会是这样的

      【讨论】:

        【解决方案4】:

        ActivatedRoute 类有一个 queryParams 属性,该属性返回 当前 url可观察 /strong>。

        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
              });
           }
        }
        

        Click here for complete article, its easy and best

        【讨论】:

          猜你喜欢
          • 2019-12-26
          • 1970-01-01
          • 2018-05-29
          • 1970-01-01
          • 2018-05-07
          • 2016-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多