簡體   English   中英

Angular組件之間的數據共享

[英]Data Sharing between Angular components

我是角度6的新手。我正在使用角度6創建一個項目。我在共享數據時遇到了問題。 這是項目結構:

1)標題組件2登錄組件3)主組件4)共享服務

我在我的標題組件中添加了基於當前路由的類。 這正在頁面刷新。 但是當我從一個組件移動到另一個組件時,這是行不通的。

這是代碼:

布局組件是:

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
</div>

標題組件:

 ngOnInit() {
    console.log(this.dataService.urlExists())
    if(this.dataService.urlExists()){
      this.url = true
     }else{
       this.url = false
     };

  }
<header class="stick-top forsticky" id="header" [ngClass]="{'gradient': url==true}">
</header>

共享服務:

urlExists(){
     this.url = this.router.url
     if(this.url == "/"){
         return false;
     }else{
         return true;
     }
 }

請注意:在頁面刷新時這是有效的..

這是因為,導航時不會重新啟動標頭組件,因為它在router-outlet 您需要監聽路由更改並相應地執行所需的操作。

因此,在Header組件中,您可以訂閱路由器事件並監聽NavigationEnd事件以檢查URL:

import {NavigationEnd, Router} from '@angular/router';
import {filter} from 'rxjs/operators';
...



constructor(private router: Router) {
    this.subscribeRouterEvents();

}

subscribeRouterEvents = () => {
    this.router.events.pipe(
      filter(e => e instanceof NavigationEnd)
    ).subscribe(() => {
       console.log(this.dataService.urlExists())
       if(this.dataService.urlExists()){
          this.url = true
       }else{
          this.url = false
       };
    });

暫無
暫無

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

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