1

I have a component that takes information from a service, and I would like to use a forEach statement to initialize component's properties. This does not work:

const variables = ['records' ,'observableComplete' ]
variables.forEach(variable => {
  this.user2RoleService[variable].subscribe( result => { this[variable] = result})
});

But this does work (but I should do it one by one)

const variable = 'observableComplete'
this.user2RoleService[variable].subscribe( result => { this[variable] = result})

Any thoughts how to solve it?

3
  • What are you doing with the updated data? Is it being displayed in the template? Commented Sep 4, 2022 at 5:19
  • Can you share implementation of user2RoleService? Commented Sep 4, 2022 at 5:58
  • Yes: the updated information is used to reflect changes on the HTML. User2Role2Service basically has a get method to be called, among others. Commented Sep 4, 2022 at 22:46

4 Answers 4

1

you should use this() instead of [].

const variables = ['records' ,'observableComplete' ]
variables.forEach(variable => {
  this.user2RoleService(variable).subscribe( result => { this[variable] =result})
});
Sign up to request clarification or add additional context in comments.

1 Comment

Don't work like this. I would like to reference to a class property. The return message with your proposal is: 'This expression is not callable.'
0

I'm assuming your user2RoleService is an instance of a class User2RoleService. Therefore, this type declaration should do:

const variables: (keyof User2RoleService)[] = ['records', 'observableComplete'];

Comments

0

I'm afraid that in strict mode you need an "ugly hack"

const variables = ['records', 'observableComplete'];

const self=this as any  //<--this is the uggly hack

variables.forEach((variable: string) => {
  self.user2RoleService[variable].subscribe((result: any) => {
    self[variable]=result;
    console.log(this.records,this.observableComplete) //<--only for check
  });
});

Comments

0

the way you are doing the assignment typescript infers it as string[], however you can improve it with the help of as const. simply do

const variables = ['records' ,'observableComplete' ] as const;

and then the type of variables will be the same tuple provided

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.