dimanche 10 novembre 2019

Angular - Encapsulate service inside component is a bad practice?

Let's assume that i have SoccerFieldComponent that has provider that called SoccerFieldService

SoccerFieldComponent:

@Component({
 providers: [SoccerFieldService]
})
class SoccerFieldComponent extends Component {
//yada yada....
}

SoccerFieldService:

class SoccerFieldService {
//a lot of observables/functions that related to the soccer field component
}

Now let's assume that SoccerFieldComponent can be used multiple times in my complex system, the only thing that will be different is the component that wrapping him, let's give him the name StadiumComponent

StadiumComponent:

@Component({
 template: "some-complex-template-that-contains-stadium-field-component.html"
})
class StadiumComponent {
}

i would really like to expose some of the SoccerFieldService data outside the SoccerFieldComponent that the StadiumComponent could use it.

My Current Solution:

Inside the StadiumComponent:

@ViewChild(SoccerFieldComponent, {static: false})
    set soccerFieldComponent(componentRef: SoccerFieldComponent) {
        if (componentRef) {
            this.soccerFieldComponentRef = componentRef;
            this.changeDetection.detectChanges();
        }
    }

Inside the SoccerFieldComponent:

get currentScore$(): Observable<string> {
        return this.soccerFieldService.currentScore$.pipe(
            distinctUntilChanged(),
        );
    }

Now i can access through the component to specific observable inside the service.

Any other ideas?

Aucun commentaire:

Enregistrer un commentaire