[英]Retrieve data from an API when routing directly to a dynamic route Angular
The question is: How would I retrieve data from an API when routing directly to a route with a dynamic value inside of it (eg a username)问题是:当直接路由到内部具有动态值(例如用户名)的路由时,我将如何从 API 检索数据
The route would look like this路线看起来像这样
{ path: '/users/:username', component: 'userDetailedComponent' } { 路径:'/users/:username',组件:'userDetailedComponent' }
The solution would be to gather the route parameter from the url.解决方案是从 url 收集路由参数。
{ path: '/users/:username', component: 'userDetailedComponent' }
From the above you are passing in the username along with the route.从上面您将传递用户名和路由。 Now at ngOnInit you can gather the user name from the url by the code below现在在 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);
});
}
In the above code, ongOnInit, we have declare a variable reading the url parameter using the ActivatedRoutes .在上面的代码 ongOnInit 中,我们使用ActivatedRoutes声明了一个读取 url 参数的变量。
this.router1.snapshot.paramMap.get('username')) will fetch the username from the url. this.router1.snapshot.paramMap.get('username'))将从 url 获取用户名。 This user name may be send to the service and the required data may be fetched.该用户名可以被发送到服务并且可以获取所需的数据。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.