2

Can a component provide a service (or something provideable) based on its inputs? In my case my component uses a service based on another firebase service and I want component to provide a new firebase service with a child, so the other service will access only the child part in the db.

In my current solution my component calls the service's setChild function to set the child, but I'm curious if it is possible in the way described above.

Thanks, Tamas

Mojtaba
  • 2,764
  • 1
  • 21
  • 24
bucicimaci
  • 1,261
  • 1
  • 9
  • 17

1 Answers1

3

No, that is not possible. When the decorator arguments are evaluated, there is no instance of the component yet.

What you can do though is to inject the service to the component where it is added to providers, and pass the value to the service. When a child also injects the same service, they share the same value:

@Injectable()
class MyService {
  ... 
}

@Component({
  selector: 'parent',
  template: 'x'
  providers: [MyService],
)}
class Parent {
  @Input() someInput;

  constructor(private myService:MyService) {
  }

  ngOnChanges() {
    this.myService.sharedValue = this.someInput;
  }
}

@Component({
  selector: 'descendant',
  template: 'x'
)}
class Descendant {
  constructor(myService:MyService) {
    myService.sharedValueChange.subscribe(val => {
      console.log(val);
    });
  }
}

for more details about creating a shared service using Observable to notify about changes see Delegation: EventEmitter or Observable in Angular2

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567