在直接路由到动态路由 Angular 时从 API 检索数据

Retrieve data from an API when routing directly to a dynamic route Angular

问题是:当直接路由到其中包含动态值(例如用户名)的路由时,我如何从 API 检索数据

路线看起来像这样

{ 路径:'/users/:用户名',组件:'userDetailedComponent' }

解决方案是从 url 中收集路由参数。

{ path: '/users/:username', component: 'userDetailedComponent' }

从上面你传递了用户名和路由。现在在 ngOnInit 中,您可以通过下面的代码

从 url 中收集用户名
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Service } from './service.service';

@Component({
  selector: 'app-userdetails',
  templateUrl: './userdetails.component.html',
  styleUrls: ['./userdetails.component.css']
})

export class UserdetailsComponent implements OnInit {

  constructor( private service: Service, private router1: ActivatedRoute) { }
  username:string ='';
  ngOnInit(): void {    
    this.username = this.router1.snapshot.paramMap.get('username'));
    this.service.getdetails('username').subscribe((data)=>{
      console.log(data);

    });
  }

在上面的代码 ongOnInit 中,我们使用 ActivatedRoutes.

声明了一个读取 url 参数的变量

this.router1.snapshot.paramMap.get('username')) 将从 url 中获取用户名。 可以将此用户名发送到服务并获取所需的数据。

希望对您有所帮助。