Angular 2: sharing data across different routes

前端 未结 3 989
死守一世寂寞
死守一世寂寞 2021-02-15 11:51

I have searched for similar questions in SO and I have not found any that addresses my specific case. There are many techniques to share data between angular components, and I h

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 12:14

    I'm not sure if the is is what you're after but if you need to share data across sibling routes you could try this.

    Create a module Import and Declare the service in the module

    import { MyService } from './my.service’;
    
    @NgModule({
      ...
      providers: [
        MyService
      ]
      …
    })
    

    Declaring the the service in the module route means we can then pass the service by reference to the child routes. Do not use the service in the parent component

    In the child route components, import the service

    import { MyService } from '../my.service’;
    

    In each component where the service should be used, do not add the service to the components metadata because we’ve already added it to the module definition. Add the service to the component constructor

    export class MyChildRouteComponent implements OnInit {  
    ...
     constructor(
        private _myService: MyService,
        private _router: Router
      ) { }
     ...
    }
    

    If you then set a service property in one child route component, you will then be able to get it from a sibling child component.

提交回复
热议问题