New to ember, I wonder what is the best way to go about this:
component.js
import Component from '@ember/component';
import { inject as service } from '@ember/service';
export default Component.extend({
ajax: service(),
url: '',
async fetchUrl() {
try {
let result = await this.ajax.request(
`api/urlgenerator`
);
this.url = result.link;
} catch (err) {
this.errorHandler.handle(err);
}
},
init() {
this._super(...arguments);
this.fetchUrl();
},
});
and my template
{{#card/banner}}
<Banner
@text="Template Button"
@action={{hash
text="Enable Launcher"
onAction=(track-action
(route-action "openUrl" this.url)
)
}}
/>
{{/card/banner}}
openUrl is simple a global method responsible for opening an external URL
--
Not too sure if this is the right way to go about it, right now it is not working, since maybe due to ember component lifecycle, the variable gets rendered with the initial value only (empty '')
However, If I hardcode the url for example, it works fine.
Can someone give me some advice on it?
In classic component style you would use this.set('url', result.link) instead of this.url = result.link. However in modern ember I would do it like this:
export default class MyComponent extends Component {
@service ajax;
@tracked url = '';
constructor() {
super(...arguments);
this.fetchUrl();
}
async fetchUrl() {
try {
let result = await this.ajax.request(
`api/urlgenerator`
);
this.url = result.link;
} catch (err) {
this.errorHandler.handle(err);
}
}
}
notice url must be @tracked.
In case it helps someone, I used this approach The Guide to Promises in Computed Properties