如何在数据服务中访问路由ID

问题描述 投票:-1回答:1

如何在数据服务中访问localhost:4200/id以将其置于某些JSON链接中?

我的意思是当我在localhost:4200/001我想获得zzz.com/001/summary的JSON

尝试过这样,但在控制台出现我有zzz.com/undefined/summary

const routes: Routes = [
  { path: ':id', component: AppComponent },
];

import { HttpClient } from '@angular/common/http';
import { Injectable, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class DataService implements OnInit{
  baseUrl = 'https://zzz.com/';
  id :string;
  constructor(private httpClient: HttpClient, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      const prodId = params['id'];
      this.id = `${prodId}`;

   })
  }
  mainData() {

    return this.httpClient.get<Header[]>(this.baseUrl + this.id + '/summary');
  }
}

我想用以下方法来做:this.id = this.activeRoute.snapshot ['_ routerState']。url并在onInit内设置超时1ms。我打电话的时候。

angular angular-router
1个回答
0
投票

你应该将params / id从调用它的组件传递给service,这样你将有最新的id来进行服务调用。

在Angular查询参数中(例如:“/ app?param1 = hallo&param2 = 123”)可以通过订阅this.route.queryParams来访问。

EX:

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    console.log('Called Constructor');
    this.route.queryParams.subscribe(params => {
        this.param1 = params['param1'];
        this.param2 = params['param2'];
    });
}

路径变量由“this.route.snapshot.params”访问

示例:“/ param1 /:query1 / param2 /:query2”

query1: string;
query2: string;
constructor(private route: ActivatedRoute) {
    this.param1 = this.route.snapshot.params.query1;
    this.param2 = this.route.snapshot.params.query2;
}

更改mainData()以接受参数:

mainData(paramId: string) {
        return this.httpClient.get<Header[]>(this.baseUrl + paramId + '/summary');
  }

现在使用您的组件访问路由参数并获取id以进行服务调用。

this.dataService.mainData('123xx').subscribe.(data => {
      // ..... do something...
})
© www.soinside.com 2019 - 2024. All rights reserved.