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

时间:2019-04-01 13:25:11

标签: angular angular-router

我如何获得对数据服务中的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。当我打电话的时候。

1 个答案:

答案 0 :(得分:0)

您应该将params / id从调用它的组件传递给服务,这样您将拥有最新的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...
})