Angular 2 passing object via route params possible?

后端 未结 1 1118
臣服心动
臣服心动 2020-11-29 10:47

I could use some advice how to approach this problem I\'m facing. To explain this best possible for you I have created a main component:

@Component({
selecto         


        
相关标签:
1条回答
  • 2020-11-29 11:32

    Just use a shared service and add it to the providers: [...] of the parent component.

    Simple service class

    @Injectable()
    export class ReservationService {
      reservation:Reservation;
    }
    

    In parent add it to the providers and inject it in the constructor

    @Component({...
       providers: [ReservationService]
    export class Parent {
      constructor(private reservationService:ReservationService) {}
    
      someFunction() {
        reservationService.reservation = someValue;
      }
    }
    

    In the child component only inject it (don't add to providers)

    @Component({...
      providers: []
    export class Passenger {
      constructor(private reservationService:ReservationService) {
        console.log(reservationService.reservation);
      }
    
      someFunction() { 
        reservationService.reservation = someValue;
      }
    }
    

    update

    bootstrap() is the common ancestor of everything and a valid option. It depends on what your exact requirements are. If you provide it at a component, then this component becomes the root of the tree that shares a single instance. This way you can specify the scope of a service. If the scope should be "your entire application" then provide it in bootstrap() or the root component. The Angular2 style guide encourages to favor providers of the root component over bootstrap(). The result will be the same though. If you just want to communicate between a component A and other components that are added to its <router-outlet> then it would make sense to limit the scope to this component A.

    0 讨论(0)
提交回复
热议问题