0
votes

How would you add a component to a View from the ViewModel. For example, I have the following:

I have a service injected into a component. Then from the component I fetch data and when I get the response I set the data property to the fetched data. After this I would like to mount the component to the View with the fetched data as a bindable.

this.service.get()
.then(response => response.json())
.then(data =>{ 
    this.data = data.results
    //Mount element to View here: <component data.bind="data"></component>
})

Im asking this question because if I set the value when fetched and on the View to this:

<component data.bind="data"></component>

It passes an empty object. I have tried using the service on the canActivate and activate methods.

Component:

export class Component{
   @bindable data
   bind(){
      console.log(this.data)
   }
}
2
What does component look like? - Ashley Grant
I updated my question. If I log data it is an empty array. - Diego Gallegos
As far as I can see, that shouldn't be an issue. Perhaps there is something breaking your code. Show the full code of your web component and service - Fabio Luz
This the whole project: github.com/DiegoGallegos4/aurelia-test. You can check the empleado folder: service, view and viewmodel are there. - Diego Gallegos

2 Answers

2
votes

I copied your code in to a gist and ran it on gist.run here: https://gist.run/?id=04907ff8d8b6d8b4aee625669d8571a3

It runs as expected for me. I even updated it to set the data inside a promise.

Now, if you want to be notified when the data property changes, you'll need to implement a function called ${propertyName}Changed(newValue, oldValue) so in this case, dataChanged(newValue, oldValue). I created a separate gist to show how you might want to change your code: https://gist.run/?id=34a01ca3f600470691d5b91c9131f33b

You'll notice in my code I didn't use the newValue and oldValue parameters. I did this on purpose to let you know that Aurelia still sets the property value. The callback is just there to let your code do stuff when the property value changes.

0
votes

The "data" field being bound to is a field on the ViewModel using your component, not a field in your component.