要将Angular参数路由作为外部链接起作用,您可以使用Angular的Router
服务和Location
服务来实现。
首先,确保您已经在Angular应用程序中正确配置了参数路由。这可以通过在路由配置文件中添加路由参数来完成。例如:
const routes: Routes = [
{ path: 'product/:id', component: ProductComponent }
];
接下来,您可以在组件中注入Router
和Location
服务,并在需要时使用它们来生成外部链接。例如,在组件中使用Router
服务来生成参数路由的外部链接:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
productId: number;
constructor(private router: Router) { }
ngOnInit() {
// 获取参数路由的参数值
this.productId = +this.router.url.split('/').pop();
}
goToExternalLink() {
// 生成参数路由的外部链接
const externalLink = `https://example.com/product/${this.productId}`;
window.open(externalLink, '_blank');
}
}
在上面的示例中,goToExternalLink()
方法使用Router
服务的url
属性来获取当前路由的URL,并从URL中提取参数值。然后,它将参数值插入到外部链接中,并使用window.open()
方法在新窗口中打开该链接。
请注意,如果您使用的是Angular的HashLocationStrategy,那么在生成外部链接时,要将/
替换为/#/
。例如:
const externalLink = `https://example.com/#/product/${this.productId}`;
通过这种方式,您可以使用Angular参数路由作为外部链接,并在需要时将其打开。
上一篇:Angular参数化自定义验证
下一篇:Angular参数未被隐藏