简体   繁体   中英

Data Sharing between Angular components

I am new in angular 6. I am creating a project using angular 6. I am coming in to a problem while sharing the data. Here is the project structure:

1) Header Component 2 Login Component 3) Home Component 4) Shared Service

I am adding the class in my header component on the basis of current route. This was working on page refresh. But when i move from one component to other this was not working.

Here is the code:

Layout Component is:

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

Header Component:

 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>

Shared Service:

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

Please note: On page refresh this is working..

It is because, your header component is not reinited when navigating as it is outside of router-outlet . You need to listen route changes and perform desired operations accordingly.

So in the Header Component, you can subscribe to router events and listen NavigationEnd events to check 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
       };
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM