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

Error in Javascript chrome when trying to determine the length of an array

I am facing an unusual issue with the JavaScript console in Chrome. When I type the following code into the console: var numbers = new Array(["/php/.svn/tmp", "/php/.svn/props"]); it returns "undefined." This leads me to believe that 'numbers' ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

A step-by-step guide on deleting an element within a div using jQuery

I am attempting to delete an HTML element using JQuery like this $('#' + divId + ' .settings_class').remove('.print_settings'); This code does not result in an error or remove the specified html element, however, the selecto ...

Is it possible to make API calls within the componentWillMount lifecycle method in React?

I've been immersed in the world of React for the past year. The standard practice within my team is to make an API call in componentDidMount, fetch the data, and then setState after receiving the data. This ensures that the component has fully mounted ...

What is the process of performing numerical calculations using jQuery?

I need to deduct certain input values from the total price. Here's the code snippet: $('.calculate-resterend').click(function(e) { e.preventDefault(); var contant = $('.checkout-contant').val(); var pin = $('.che ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

The intricate scripting nestled within the jQuery function

When using jQuery, I am looking to include more codes within the .html() function. However, I also want to incorporate PHP codes, which can make the writing style quite complex and difficult to read. Is it possible to load an external PHP/HTML script? fu ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

Attempting to modify the information within the #content division of a webpage through the activation of a linked image within a jquery slideshow

I'm completely stuck on this one, even though I'm relatively new to jquery. My goal is to design a webpage where there is a slideshow of products at the top, and when a user clicks on one of the products, it should update the main #content div w ...

Getting request parameters within Model in Loopback can be done by accessing the `ctx`

common/models/event.json { "name": "Event", "mongodb": { "collection": "event" }, "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "http": { "path": "organizer/:organizer_id/events" }, "properties": {}, "va ...

Switching HTML text by clicking or tapping on it

I'm currently working on a website that will showcase lengthy paragraphs containing complicated internal references to other parts of the text. For instance, an excerpt from the original content may read: "...as discussed in paragraph (a) of section ...

What is the best way to sequence the functions in an AJAX workflow?

I'm currently working on optimizing the execution order of my functions. There are 3 key functions in my workflow: function 1 - populates and selects options in a dropdown using JSON function 2 - does the same for a second dropdown function 3 - ...

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

pure-react-carousel: every slide is in view

Issue I am encountering a problem where the non-active slides in my container are not being hidden properly. This results in all of the slides being visible when only one should be displayed. Additionally, some slides are rendering outside of the designate ...

What is causing this code to malfunction?

Currently delving into the world of Ajax, I've been following a tutorial and have crafted the script below: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function MyFunction(){ var xmlhttp; if(windo ...

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

When using React, it's important to verify if the page has been refreshed before updating the local storage based on the GraphQL query. If the page

Currently, I am working on implementing a hit counter feature that increments each time a user clicks a button. The setup involves GatsbyJS with React and utilizes a lambda function to store the count in FaunaDB. Additionally, the client-side functionality ...