簡體   English   中英

如何在角度相同的組件中通過更改URL來加載頁面上的內容?

[英]How can I load content on page with a change in URL in the same component in angular?

我試圖在同一組件內獲取一個頁面,以在URL更改后加載一些內容。

myComponent.ts

ngOnInit(){
  this.router.events.subscribe(res=> {
    if (this.router.url.split('?')[0].split("/").pop() === 'invitations'){
      console.log('do something');
    }
  }
}

myModule.ts

const routes: Routes = [
           { 
             path: 'fancy_app', 
             component: myComponent,
             children:[
               {path: 'invitations', component: myComponent}
             ]
           }
];

當我這樣做時,以及當我第一次嘗試訪問路線:fancy_app / invitations時,我注意到“做某事”未加載。 但是,當我再次單擊該鏈接時,它將起作用。 所以我猜ngOnInit不是這個地方嗎? 我如何確保它在我第一次訪問URL時加載?

好的,我把它放在可以工作的構造函數中。 仍然不清楚為什么在ngOnInit上不起作用。 據我了解,ngOnInit是在構造函數實例化該類之后調用的。 我試圖避免使用構造函數。 有人可以告訴我為什么ngOnInit在我第一次嘗試訪問URL時不起作用嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM