我正在為一個SaaS應用程式的登陸頁面撰寫一個angular應用程式。SaaS通過URL http://localhost:4200/token=<token>重定向到angular應用程式,而angular則迅速改變為主頁組件http://localhost:4200/#/。
我需要獲得<token>的值來在代碼中使用。我如何在angular應用程式中復制初始的URL?
uj5u.com熱心網友回復:
你可以使用angular router來獲取token,如果它的格式是你所描述的那樣。
從@angular/router中匯入angular router。
constructor(router:Router){}.
yourRoute ?:string;
ngOnInit(){
this.yourRoute = this.router.url.split('/').pop()。
}
供將來參考:
如果這不起作用,你可以使用激活的路由庫。
讓我知道。
uj5u.com熱心網友回復:
- 在你的AppRoutingModule中: 。
從'@angular/router'匯入{ Routes }。
const routes:Routes = [
{
path:'',
component: MainComponent, // 你的主組件,它將會得到令牌。
pathMatch: 'full
},
{
path:'/:token',
組件。MainComponent, // 你的主組件,它將獲得令牌。
},
... // 你的其他路由。
{
path:'xxx',
組件。XxxComponent
},
{
path:'**',
redirectTo: ''
}
]
NgModule({
進口。[RouterModule.forRoot(routes)]。
出口。[RouterModule]。
})
輸出類AppRoutingModule {}。
- 記得在你的AppModule中匯入你的AppRoutingModule: 。
...
從'./app-routing.module'匯入{ AppRoutingModule }。
...
進口。[
...
AppRoutingModule。
...
],
- 在你的MainComponent中,它將會得到令牌 。
import { ActivatedRoute } from '@angular/router';
令牌:字串
建構式(private activatedRoute: ActivatedRoute) {}。
ngOnInit(): void {
this.token = this.activatedRoute.snapshot.paramMap.get('token')。
// 如果你要接收計數的令牌。
// this.activatedRoute.params.subscribe( _token => this.token = _token); }
最后,你只需要像這樣呼叫angular。
**http://localhost:4200/token**
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/323560.html
標籤:
上一篇:如何將我的承諾改為可觀察的?
