Home > Mobile >  Setting variable values on a component that is passed to a service
Setting variable values on a component that is passed to a service

Time:12-31

I have a service that's trying to hydrate values of a given component. Basic functionality:

  1. Service will accept a component into its method
  2. Do an HTTP request to retrieve data
  3. Update @Input variables of the component once data resolves

I wrote some pseudo code below to elaborate what I'm trying to do. Is this possible to do?

Service method:

  public mapTo(component: any): void {
    httpCall.then(result => {
      component.inputVariable = result.data;
    });
  }

Component:

export SomeComponent {
  @Input() inputVariable = null; // expecting this to be updated by the service
  constructor(private modelService: ModelService) {
    this.modelService.mapTo(SomeComponent);
  }
}

CodePudding user response:

What you're trying to do is a little bit antipattern in Angular world.

  public mapTo(component: any): Observable<any>{
    return httpCall.pipe(result => {
      map(result => result.data)
    });
  }

and on the component side:

SomeComponent {
  inputVariable = null; // expecting this to be updated by the service
  constructor(private modelService: ModelService) {
    this.modelService.mapTo().subscribe(result => this.inputVariable = result);
  }
}

If that's not possible, you can try to inject component instance to the service. So in your service file

xxxxx.service.ts

Injectable()
export class Myservice{
 constructor(@Inject(forwardRef(() => SaveComponent)) saveComponent){}

 public mapTo(): Observable<any>{
    return httpCall.pipe(result => {
      map(result => this.saveComponent.inputVariable = result.data)
    });
  }
}

v3 - pass the component instance

Service method:

  public mapTo(component: any): void {
    httpCall.then(result => {
      component.inputVariable = result.data;
    });
  }

Component:

export SomeComponent {
  @Input() inputVariable = null; // expecting this to be updated by the service
  constructor(private modelService: ModelService) {
    this.modelService.mapTo(this);
  }
}

stackblitz: https://stackblitz.com/edit/angular-ivy-hkwj81?file=src/app/hi.component.ts

  • Related