简体   繁体   English

Angular组件之间的数据共享

[英]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. 我是角度6的新手。我正在使用角度6创建一个项目。我在共享数据时遇到了问题。 Here is the project structure: 这是项目结构:

1) Header Component 2 Login Component 3) Home Component 4) Shared Service 1)标题组件2登录组件3)主组件4)共享服务

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 . 这是因为,导航时不会重新启动标头组件,因为它在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: 因此,在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