What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the properties of the user's organization within my routes/controllers.

This is my user model:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  email: DS.attr('string'),
  organization: DS.belongsTo('organization', { polymorphic: true, async: false } )
});

I've created a service to retrieve the user like so:

//app/services/session-account.js    
import Ember from 'ember';
    import jwtDecode from 'npm:jwt-decode';
    const { inject: { service }, RSVP } = Ember;
    export default Ember.Service.extend({
      session: service('session'),
      store: service(),
      loadCurrentUser() {
        return new RSVP.Promise((resolve, reject) => {
          const token = this.get('session.data').authenticated.access_token;
          if (!Ember.isEmpty(token)) {
            var token_payload = jwtDecode(token);
            return this.get('store').findRecord('user', token_payload.user_id, { include: 'organization' }).then((user) => {
              this.set('account', user);
              this.set('organization', user.organization);
              resolve();
            }, reject);
          } else {
            resolve();
          }
        });
      }
    });

Upon logging in, I trigger loadCurrentUser and have confirmed that it successfully retrieves the user from the back-end (including the organization data in the jsonapi response). However, although I can inject the service into my controllers/routes, access the user, and fetch its direct properties, I am unable to access any properties of the related organization using either

myservice.get('currentUser.organization.name')
(returns as undefined) or
myservice.get('currentOrganization.name')
, which results in the error message:
Uncaught TypeError: Cannot read property '_relationships' of undefined
.

When loading a user as a model and referencing the properties of user.organization in a template, everything functions correctly. But on the JavaScript side, I am unable to access the organization model.

EDIT: I also attempted the following variation:

return this.get('store').findRecord('user', token_payload.user_id, { include: 'organization' }).then((user) => {
  this.set('currentUser', user);
  user.get('organization').then((organization) => {
    this.set('currentOrganization', organization);
  }, reject);
  resolve();
}, reject);

Despite drawing inspiration from the ember guides relationship documentation, this version throws the error TypeError: user.get(...).then is not a function.

Answer №1

If you're looking to make some changes, here are a couple of suggestions:

1) Swap out

this.set('organization', user.organization);
for
this.set('organization', user.get('organization'));

2) Add

console.log(user.get('organization'))
right after this.set('account', user); and see what it prints out

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we transfer functions between files in JavaScript when creating a service library?

There's a piece of code located in my identity service that I'm working with. export function sumbitLogin(username, password) { console.log(username, password); } I want to simplify the process of accessing services in my components without ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Issue with passing values from JavaScript to PHP not working as expected

For some reason, I just can't seem to get this line of code to work. It's like my brain is not cooperating: var all = color.val('all'); $('#cssColor" + <?php echo $page ?> + "', parent.document).attr("background-color", ...

Set the title attribute according to the content of the <p> tag

Recently, I encountered a situation where I had numerous p tags with a specific class (let's call it .text). My task was to include the title attribute containing the text of each tag. For example: <p> Hello, world </p> This would resul ...

The functionality of AngularJS's state URL depends on numerical URLs for navigation

Currently, I am utilizing the following URL in my state setup: .state('forum.spesific', { url: '/:articleId', templateUrl: 'modules/forum/client/views/forum.client.view.html', controller: 'forumCont ...

Learn how to run a Linux bash command by clicking a button, where the command is generated from user input

HTML: I am presenting two inputs here <input id="range3" type="range" min="0" max="255" value="0" /> <input id="num3" min="0" max="255&q ...

AngularJS tips for resolving an issue when trying to add duplicates of a string to an array

Currently dealing with a bug that occurs when attempting to push the same string into an array that has already been added. The app becomes stuck and prevents the addition of another string. How can I prevent the repeat from causing the app to get stuck w ...

Error! React is unable to find the window object

I recently added the "react-speech" package to my application in order to incorporate text-to-speech functionality. However, upon importing the package, I encountered an error that has been challenging to resolve despite extensive research. Any assistance ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

What causes the Woocommerce checkout button to be blocked on the checkout page?

I am perplexed by WooCommerce's decision to block this section of the screen with an overlay. Under what circumstances would it do so? checkout page screenshot ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

JavaScript- Tabbed Navigation with Lists as the Content

Currently, I am facing a frustrating issue in finding a suitable solution. My website uses tabs that utilize the UL, LI system, similar to most tab systems found in tutorials. The problem arises because the javascript on my site interferes with using the ...

Comparison of passwords in Nodejs is hindered by Bcryptjs

Struggling to compare passwords using bcryptjs for JWT authentication. Unable to successfully verify the password during login to sign the token and send it to the client. Issue The problem arises when trying to use the .compare() method in bcryptjs and ...

Generating a JavaScript array in PHP

As I work on developing a dynamic Google Geochart, one key aspect is creating an array to hold the data. The structure includes the country as the unique identifier and the color value to determine the map shading. arrayData = [['Country',' ...

What is the process for sending a request and obtaining a response from a REST API using JavaScript?

I have a private server set up on my computer with a built-in REST API. The base URL for the API is: . I am now looking to develop a client application for this server using the API. To authenticate on the server, the API endpoint is baseurl/login with the ...

AngularJS Resource GET Request Unsuccessful

Is there a way to verify if a resource failed to be fetched in AngularJS? For instance: //this is valid syntax $scope.word = Word.get({ id : $routeParams.id },function() { //this is valid, but won't be triggered if the HTTP response is 404 or an ...

Discover the color value within an array that begins with the "#" symbol

In my PHP code, I have written a function that extracts values from a CSS file and creates an array. Now, I need to loop through this array and create another array that only contains color values (strings starting with #). The challenge is that the length ...

Tips for extracting an XML value from an API

I'm attempting to showcase a value retrieved from an API (specifically used by PRTG software to extract information). Here is the link to the API: The API provides an XML file structured like this: <?xml version="1.0" encoding="UTF-8"?> <ch ...