ember.jsember-data

Override computed property in Ember 4 adapter


In the "new" class style of Ember / JavaScript (at least new to me), I am having trouble adapting old tutorials to set a computed property in my JSONAPIAdapter.

export default class ApplicationAdapter extends JSONAPIAdapter {
  @service session;

  headers: computed('session.isAuthenticated', 'session.data.authenticated.token', function() {
    if (this.session.isAuthenticated) {
      return {
        Authorization: `Bearer ${ this.session.data.authenticated.token }`,

Results in

$TMPDIR/embroider/b3d2a6/adapters/application.js/application.js: Unexpected token (8:9)

   6 |   @service session;
   7 |
>  8 |   headers: computed('session.isAuthenticated', 'session.data.authenticated.token', function() {

The docs ( https://api.emberjs.com/ember-data/4.3/classes/JSONAPIAdapter/properties/headers?anchor=headers ) imply that this should work, but I think the @service session line is messing things up.

What is the correct way to set the headers property an Ember 4 class in 2022?


Solution

  • Not sure exactly what error you're seeing, but you should be able to replace this with a getter

    get headers() {
      if (this.session.isAuthenticated) {
        return {
          Authorization: `Bearer ${ this.session.data.authenticated.token }
        }
      }
    }
    

    You can see a working example in our addapter