vendredi 31 janvier 2020

Ember JS: Call component action from another component

I am new to ember JS and after looking through the doc I still have no idea or don't understand how to achieve the following.

I have a navbar component that includes a menu button component

//components/nav-bar.hbs

<nav>
   <LinkTo class="btn-1" @route="contact"><span>Contact</span></LinkTo>
   <LinkTo class="btn-1" @route="about"><span>About</span></LinkTo>
   <MenuButton>Menu</MenuButton>
</nav>

When this button is clicked I would like to toggle another component which is not a parent nor a child of menu-button component, nor of the nav-bar component

//components/nav-aside.hbs
<div class="core_page_cover">

</div>
<aside class="core_menu_aside">

</aside>


//components/nav-aside.js
import Component from "@glimmer/component";
import { action } from "@ember/object";

export default class NavAsideComponent extends Component {
   @action
   toggle() {
       //toggle expanded | retracted class
   }
}

I have no idea how to call the toggle action when clicking on the button and I guess I am missing something...

Thanks a lot.




how to backtrack an ember application code

How to understand an ember application code .

I want to backtrack where a variable is defined from web page to component.

example :

in web page Title : "Wonder boy"

in template it is mentioned as

 

     title = field.label

 

but in the component for this template i am not able to find the varaible field nor field.label . can you please provide me any resource to understand how to backtrack a ember application from web front to variable . thanks .




jeudi 30 janvier 2020

Is there anyway to debug typescript using the ember cli with vscode?

I searched on stackoverflow and found this post: How to debug Javascript-Code produced and served by ember-cli?

however, it was made in 2014 and I hope maybe some features were added or anything.

I am trying to place breakpoints in vscode in my typescript files. However, it doesn't seem to work at all, because the ember cli doesn't map ts to js files that it creates.




Ember.js combining two objects from datastore to a string

I have gathered 1 string from 2 different places in the datastore, an URL and a nickname, what I want to do is combine these two so I can "pre-select" in my dropdown. The problem is, if I check the value within the "declaration of the variables" then I get the text result alerted, but if I alert afterwards when I'm trying to combine the two strings, I get [Object object], [Object object] instead. And for some reason I get the Object Objects first, and then the URL and then the nickname, which isn't even the correct order..? The code looks like this:

preSelect: function (orgSiteId, orgId) {
    'use strict';
    var url = this.get('store').find('orgSite', orgSiteId).then(function (orgSites) {
        alert(orgSites.get('url'));
        return orgSites.get('url');
    }.bind(this));
    var nickname = this.get('store').find('org', orgId).then(function (orgs) {
        alert(orgs.get('nickname'));
        return orgs.get('nickname');
    }.bind(this));

    this.set('testFillSelect', nickname + ', ' + url);
    alert(this.get('testFillSelect'));
},

Is this a situation where I want to use computed properties or observer? I'm new to Ember.js and this feels like it's supposed to be simple.




mercredi 29 janvier 2020

How to mutate an array's value in "each" helper in Ember JS (Octane)

I have an array of strings passed as an argument to a component, inside the component I am using "each" helper to render each string in a text input. I tried the following approach.

MainComponent.hbs
<Component @model=/>

//Eg: model.list = ["Jack", "Sparrow"];

Component.hbs
<div>
    
    <div>           
         <PaperInput @value= 
            @placeholder="Enter a Name"
            @onChange=/>        
    </div>
    
</div>

I am running into the error "Uncaught (in promise) Error: Assertion Failed: You can only pass a path to mut". Would really appreciate if anyone can let me know What's going wrong here.




How to make components rendered via helper independent

I have few instances of component (let's call it <Row />) with given template:

    

I' calling <Row /> component from <Terminal /> component like this:


  <Row @result= @confirm= @resultComponentName=/>

<Terminal /> component has property:

@tracked resultComponentName;

which is handled in action:

    if (cmd.resultComponentName) {
      this.resultComponentName = cmd.resultComponentName;
    } else {
      this.resultComponentName = 'result-component';
    }

now I want to change @resultComponentName in only one instance but when I am changing @resultComponentName all of the component <Row /> instances re-render.

How can I prevent that behavior and make every instance independent? Thanks in advance!




How can I use the same name for singular and plural form in Ember?

I have a type media. I would like to use that name for both the singular and the plural forms. but I am struggling to figure out how to do so. I imaging it is by adjusting Ember.Inflector but I have sent every variation at it that I can think of with no luck.

Note: I am currently stuck on Ember 1.13, and upgrading it really isn't feasible right now.




How to display an object properties on the page from an array of objects in Ember.js?

I have a website that has a list of products when a user clicks on 'Add to cart' he adds a product to the card (product is saved in a Local Storage). I want to display a list of projects added to the card from the Local storage on my page, but all I get is: [object Object] [object Object] [object Object]. How do I display the properties of these objects on my page? (I have a JSON file with the names, pictures, prices of the product, the data to display is coming from my JSON file)




mardi 28 janvier 2020

Ember js - Cannot generate URL with dynamic segments using urlFor method

Point me what’s wrong with my code,

I can able to generate URL using urlFor() when I’m in the route “/1/1/orders”. but I’m unable to generate a URL in the application route.

Kindly advise me.

here is the reference ember-twiddle




Fetching content from file and Ember CLI Mirage

I have a component in my Ember app which returns data from a static markdown file.

  didInsertElement() {
    fetch('markdown/faqs-content.md').then(response => {
      response.text().then(result => {
        this.set('markdown', result);
      });
    });
  }

When the app runs, the request goes to http://localhost:4200/markdown/faqs-content.md and everything works fine.

However, in mirage, I get this error:

Mirage: Your app tried to GET '/markdown/faqs-content.md', but there was no route defined to handle this request. Define a route for this endpoint in your routes() config. Did you forget to define a namespace?

The above happens, even though the following is included in mirage/config.js:

this.passthrough();

Presumably, this is because the API namespace is not included in the request URL.

The problem can be solved by adding the full URL to passthrough:

this.passthrough('https://localhost:4201/markdown/faqs-content.md');

Doing this has two issues:

  1. I don't always know the port that the app is served on, and
  2. I don't want to lose the functionality of using this.passThrough(), which automatically invokes pass through for any API requests where there is no corresponding route in mirage/config.js.

I thus have 2 questions.

  1. In config.js, is there any way of getting port that Ember server is running on, to allow something like https://localhost:${port}/markdown/faqs-content.md?

  2. Is there a way that I can configure Mirage to pass through for the request to https://localhost:4201/markdown/faqs-content.md, and still allow it to pass through for any other requests that don't have a corresponding route defined?




dimanche 26 janvier 2020

After upgrade to ember 3.15, helpers that yield promised recompute infinitely

I am having trouble zeroing in on this bug, but something happened when I upgraded from 3.13 to 3.15. In some (but not all) templates where I use the result of a helper in a let block, the helper will be rerendered infinitely.



  


If I don’t do anything with data, it’s fine. As soon as I try to use data for anything, it blows up. Specifically, I have examples of troubles with both promises and concurrency tasks. They’re very baked into my frameworks so it’s hard to break them out one at a time. I’ll have to work on that.

I’ve seen examples of how this has happened in the past due to bugs such as this one:

https://github.com/emberjs/ember.js/issues/14351

I also read about helpers that modify arguments to the helper thereby causing a rerender. But I’m pretty sure I checked that well and that’s not the problem.

The browser will slow to a crawl, and if I put console.log(‘hi’) statement in the helper’s compute function, I’ll see thousands of ‘hi’s. So I know it’s getting called over and over

I know this isn’t a very complete question, but I’m in a bind now and it’s the best I can scrape up.

Is there anything that can happen in the octanifying of my app that could make this happen?




samedi 25 janvier 2020

Redirecting to another route ember js

Case I have two routes for eg(1.parking 2.Car) Parking route has dynamic segment like parking id(/park/1) Car has car id(/car/76/)

When i take transition from parking route to car route ,i need to define the url with parking id and car id




emberjs without cli (version 3)

This question has been answered for earlier versions of emberjs (https://www.tutorialspoint.com/emberjs/emberjs_environment_setup.htm).

My question concerns emberjs version 3:

Is it still possible to load emberjs from a CDN and have an application be run dynamically without the need to bundle it using the ember-cli?

What I am specifically looking for is a single-file-example which loads all the needed resources from a CDN and then runs a simple Hello-World with maybe a route (or two)

I know, the recommended way is to use the CLI. I am just curious, whether it is technically possible to run emberjs-applications without CLI.




jeudi 23 janvier 2020

Ember 3.15, seperating components javascript from template files

Is it possible to separate the templates .hbs from component class javascript .js in Ember 3.15 Octane.

A folder structure like:

app/
   components/
     js/
     hbs/



Ember Octane: Testing async action on controller

Having the following controller and tests:

app/controllers/application.js

import Controller from '@ember/controller';
import { action } from '@ember/object';

export default class ApplicationController extends Controller {
  flag = false;

  @action
  raiseFlag() {
    this.flag = true;
  }

  @action
  async raiseFlagAsync() {
    await new Promise(resolve => setTimeout(resolve, 1000));
    this.flag = true;
  }
}

tests/unit/controllers/application-test.js

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Controller | application', function(hooks) {
  setupTest(hooks);

  test('it raises flag', function(assert) {
    let controller = this.owner.lookup('controller:application');
    assert.equal(controller.flag, false);
    controller.send('raiseFlag');
    assert.equal(controller.flag, true);
  });

  test('it raises flag asyncronously', async function(assert) {
    let controller = this.owner.lookup('controller:application');
    assert.equal(controller.flag, false);
    await controller.send('raiseFlagAsync');
    assert.equal(controller.flag, true);
  });
});

The first test case passes. The second test case fails (the async one)

What is the ember-octane way of waiting for the async action?




Mouse Click not working for google.maps.places.Autocomplete

I have an issue with google.maps.places.Autocomplete, strangely the same code is working OK on another page with all other similar assets except the input control is in a div that is displayed using slick slider on the page where i am having the issue . On this page I still can use keyboard keys to select the search results. But when I try to left click using mouse on search results, it do not change any thing infact the result div is not being hidden if I click some where else on page. Somehow Google Api is not binding click events to Search Results when input control is in sliding div.

Following is my code. Please help.

 var _g_autocomplete;
function initializeGoogleSearch() {
  var crtlId = 'txtSearchInput';
  _g_autocomplete = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById(crtlId)),
      { types: ['geocode'] });
  google.maps.event.addListener(_g_autocomplete, 'place_changed', function() {
  var place = _g_autocomplete.getPlace();
    //console.log(place);
  });

}



mercredi 22 janvier 2020

Mutate changeset field value with ember-bootstrap custom element

I'm on Ember 3.15 (Octane). With the following setup

template

<MyComponent
  @changeset=
  @onSubmit=
/>

component

<BsForm 
  @model=
  @formLayout="horizontal"
  as |form|>

  <form.element
    @label="My Custom Field"
    @property="myField" as |el|>

    <BsButtonGroup
      @value=""
      @type="radio"
      as |bg|>

            // options is a string array ['first', 'second', 'third']
        <bg.button
          @type="info"
          @value=""
          @onChange="" >
          
        </bg.button>
      

    </BsButtonGroup>
  </form.element>
</BsForm>

The problem I'm facing is that the changeset-set is not changing the value of myField when I change the radio button selection. I initially tried @onChange="" but that didn't work.




How to create a object in ember-cli-mirage?

I have a foo model that hasMany bar and bar belongsTo baz. How can I include the creation of baz when a foo is created together with it's bar? Whenver a foo is created a 10 bar must create and a baz is created for each bar

On my /factories/foo.js I have a

  afterCreate(foo, server) {
    server.createList('bar', 10, { foo });
  }



mardi 21 janvier 2020

How to access the content of /apple-app-site-association in Ember.js?

I got tricky quesiton. How would I get the content of a file if access this url https://www.someUrl.com/app-app-site-association and once the url is entered on the browser the content below will show?

{
  "applinks": {
    "apps": [],
      "details": [
        {
        "appID": "9F33946S35.foo.bar.baz",
        "paths": ["*"]
        }
    ]
  }
}



EmberJS: force transition to parent route

I've got two routes: a main route, called parent, and a child route of it called parent.child. When something happens (let's call it X) in parent.child, I want to transition to parent, but since technically we're already there, Ember does nothing.

// 'parent.child' controller
this.transitionToRoute('parent');

So I want to know if there's a way to force this "transition". The reason is that there's code in parent that needs to re-run after X occurs.




lundi 20 janvier 2020

How to track a nested attribute in a Glimmer component?

I am building my first Glimmmer component in Ember and I had something like this in my template:

<p>Some val: </p>

I then made a corresponding .js component file and thought I would try to remove the long path from the HTML.

My first attempt was to make a getter:

get val() {
  return this.my_obj.some.deeply.nested.path.to.val;
}

With the template now:

<p>Some val: </p>

That works initially and displays the starting value assigned to the val variable, but it does not update when the underlying val changes.

So I thought I would try marking the getter as tracked, but that made the output disapear:

@tracked val;

get val() {
  return this.my_obj.some.deeply.nested.path.to.val;
}

I then tried this, but it's not valid syntax:

@tracked this.my_obj.some.deeply.nested.path.to.val;

So how should this be handled in a Glimmer component?

Surely the solution is not for the HTML to reference a deep path like this everytime the variable is referenced, however the new Ember docs, nice as they are, leave me none the wiser on this relatively simple/common case.




How do you create nested dynamic routes with ember.js where child route replaces parent's template?

On Ember 3.15 (Octane)

I'm trying to create the following routes in my application

/cars
/cars/:car_id
/cars/:car_id/:model_id

The first two are fine and I've been able to create them using ember-cli

ember g route cars
ember g route cars/car

The problem with the third one is that I need the model template to be shown under the cars template, ie. replace the car template. So if I put an on the car template, the model template is rendered in it fine but obviously with that nothing happens when I navigate to /cars/5/2

My router looks like this

Router.map(function() {
  this.route('cars', function(){
    this.route('car', { path: ':car_id'}, function() {
      this.route('model', { path: ':model_id' });
    });
  });
});

I've tried using an index route ember g route cars/car/index but the problem with this that the params are not available in the index route and can only be accessed on the car route.

As plan b I've created the model route as a top level route (based on this answer), but I'd like to achieve the above because of a few reasons

  • it seems more logical ie, structuring the app based on the nesting of the routes
  • I have many nested routes and creating all of them as first level routes will become hard to maintain
  • (probably the most important) ember doesn't apply the active class correctly with this configuration. For example if I have a navbar with Cars as an link, I'd want it to have the active styling on all three pages. But this doesn't work anymore because the second route will be called something like car and the third one something like model.



dimanche 19 janvier 2020

Using emberjs query parameters with a subroute 'transitionTo'?

I'm trying to 'transitionTo' a sub-route of the current route and the seems to be ignored - there's no error it just doesn't happen.

router.js

this.route('produce', function() {
    this.route('download-form');
    this.route('download-form-new', {path: '/:prlid_for_form/:prrefnum_for_form/download-form'});   
});

routes/produce

From the 'produce' route this works as you would expect,

this.transitionTo('produce.download-form');

... that is the current route becomes 'produce/download-form', ...but if I replace that with this ...

 this.transitionTo('produce.download-form-new', { queryParams: { prlid_for_form: "99", prrefnum_for_form: 'ABC'} });

... it gets executed without error but no transition takes place.

This is in Ember 3.8.




How to add a child component to the main component through javascript in Ember Octane

I have a component with a placeholder and button. Whenever this button is clicked I want to instantiate and add a child component to the placeholder div. It’s like adding rows on button click. How do I implement this behaviour.

Here is the pseudo code.

MainCompoent.hbs

<div id="placeHolder>   </div>
<button onClick=> Add </button>

MainCompoent.js
 @action
 clickAdd() {
   //How to initialize Row Component and add to the placeHolder
}

RowComponent.hbs
  <div>    
    <input name>  
    <input age>   
 </div>

I tried something like this but it did not work as expected.

MainComponent.js

@action
addCondition (){       
    document.getElementById("placeholder").innerHTML += `<RowComponent/>`;
}

enter image description here




How do I add isolated partial authenticator:oauth2 functionality to an Ember app

I'm using AuthenticatedRouteMixin and ApplicationRouteMixin from ember-simple-auth with ember-simple-auth-token to provide a TokenAuthorizerMixin with authenticator:jwt for my app. They both use a service called session to provide functionality.

Now I need to implement access to a foreign endpoint which uses oAuth. My app receives an oAuth bearer access_token, refresh_token and expires_in with the jwt that can be used for this route.

How can I automate the refreshing of this token client-side without touching the application-wide session service in use by authenticator:jwt?

How can I send authenticator:oauth2 headers in stead of authenticator:jwt headers on one (or a few) routes only, when aforementioned mixins use the same session service internally?




samedi 18 janvier 2020

ember-changeset-validations not validating properly

I'm on Ember 3.15 (Octane) and trying to get ember-changeset-validations working by following the examples on their github but having a hard time getting it to validate. There are no (code related) errors in the console but changeset.isValid always returns true.


import {action} from "@ember/object";
import MyValidationClass from '../Validations/myValidations';

export default class MyController extends Controller {
  MyValidationClass;

  @action
  submit(changeset) { 
    changeset.save()
  }
}

--


<MyComponent
  @changeset=
  @onSubmit=
/>

--


export default class MyComponent extends Component {
    async submit(changeset) {
      await changeset.validate();
      console.log(changeset.isValid);   // returns true even when the validation should fail
    }
}

--


import {
  validateLength,
  validatePresence
} from 'ember-changeset-validations/validators';

export default {
  title: [
    validatePresence(true),
    validateLength({ min: 44 })
  ]
};



how to inject a service in Ember App with Typescript

I am following this guide: https://v4.chriskrycho.com/2018/typing-your-ember-update-part-1.html

Here I have a service, which only have one function findAllContacts:

export default class ContactPicker extends Service {
  findAllContacts(): Promise<Contact[]> {
    return Promise.resolve(getContact());
  }
}

declare module '@ember/service' {
  interface Registry {
    'contact-picker': ContactPicker;
  }
}

and a phonebook component:

import Component from '@ember/component';
import Computed from "@ember/object/computed";
import ContactPicker from '../services/contact-picker';
import { inject as service } from '@ember/service';
export default class PhonebookView extends Component {
  contactPicker: Computed<ContactPicker> = service('contact-picker');

  didInsertElement() {
    let contacts = this.contactPicker.findAllContacts(); //error
  }
};

but I got typescript error when call this.contactPicker.findAllContacts(): Property 'findAllContacts' does not exist on type 'ComputedProperty'.ts(2339)

how to inject service with Typescript?




Ember js build throws null coalescing error

I'm following the guide here to create getters in my component. However following the guide as it is gives me an error

Support for the experimental syntax 'nullishCoalescingOperator' isn't currently enabled

Searching through the guides, I couldn't find any documentation on how to enable this. I've tried this in my ember-cli-build.js file but that didn't work

'ember-cli-babel': {
  includePolyfill: true,
  nullishCoalescingOperator: true
}

and

'ember-cli-babel': {
  includePolyfill: true,
  nullishCoalescingOperator: 'enabled'
}



vendredi 17 janvier 2020

Ember Js: Error when navigating between dynamic segment of a same route (Failed to excecute 'insertBefore')

I get an error when navigating between dynamic segment of the same route for example when I navigate between /project/my-project/ to /project/my-project/gallery everything works fine.

But when I navigate from /project/my-project/ to /project/my-other-project or /project/my-project/gallery to /project/my-other-project

Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node

Uncaught (in promise) DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

This is part of my application route structure enter image description here

which is written in router.js like this

this.route('project', {path: '/project/:seo_url'}, function() {
 this.route('gallery');
});

this is what i wrote in project.hbs

<Project::Banner @title="" @image="assets/images/projects/project-banner.jpg"/>
<section>
    <div class="container">
        <div class="tabs has-border-bottom">
            Description
            Gallery
            Error When I click this
        </div>
    </div>
</section>


<Home::ProjectSlider @title="Latest Projects" @projects=/>

Project::Banner and Home::ProjectSlider are components and I don't know if they are relevant to this problem.




jeudi 16 janvier 2020

Generate jwt web auth tokens in ember-cli-mirage (or any JavaScript) for use in your ember app

I work on an Ember team that implemented djangorestframework-simplejwt for our API security. It's a good API solution, but our mirage user was getting logged out after a period of time and could not log back into our app (for testing, development). I traced the problem down to how jwt works, and the fact that I had pasted static jwt tokens in our mirage config /login endpoint.

jwt or JavaScript Web Tokens contain an expiration date, set on the server. Once that expiration date passes, the client cannot be auth'ed into the app anymore, until the server sends a new token with a future expiration date. This was a problem for our mirage ENV, because the mirage endpoint for /login was returning a static jwt token which I had copy/pasted from our backend response. The workaround was to get new tokens from our backend, paste them into our mirage config and use them until they expire, which is not a true permanent solution to this problem.

After a LOT of trial and error (and learning way too much about jwt), I came up with this solution, which creates a valid jwt token with an expiration date 7 days in the future. It only requires crypto-js (npm install crypto-js), a very lightweight library with many crypto functions, but no dependencies:

import CryptoJS from 'CryptoJS';

const generateTokens = function(secretKey) { // fn to generate jwt access and refresh tokens with live date (+7 days) expiration
  let newEpochDate = new Date().valueOf();
  newEpochDate += 6.048e8; // add 7 days padding
  newEpochDate = Math.trunc(newEpochDate / 1000); // convert to Java epoch date value
  let tokenObjBase = {
    'typ': 'JWT',
    'alg': 'HS256'
  };
  let tokenObjAccess = {
    'token_type': 'access',
    'exp': newEpochDate,
    'jti': '83bc20a2fb564aa8937d167586166f67',
    'user_id': 24865
  };
  let tokenObjRefresh = {
    'token_type': 'refresh',
    'exp': newEpochDate,
    'jti': '83bc20a2fb564aa8937d167586166f67',
    'user_id': 24865
  };

  let base64urlEncode = function (obj) {
    let base64url = CryptoJS.enc.Utf8.parse(JSON.stringify(obj)).toString(CryptoJS.enc.Base64);
    base64url = base64url.replace(/=/g, '').replace(/\//g, '_').replace(/\+/g, '-'); // crypto-js doesn't have base64url encoding; we must manually make the tokens URL safe
    return base64url;
  }
  let tokenBase = base64urlEncode(tokenObjBase);
  let tokenAccess = base64urlEncode(tokenObjAccess);
  let tokenRefresh = base64urlEncode(tokenObjRefresh);

  let signatureAccessArray = CryptoJS.HmacSHA256(tokenBase + '.' + tokenAccess, secretKey); // crypto-js returns a "wordarray" which must be stringified back to human readable text with a specific encoding
  let signatureAccess = signatureAccessArray.toString(CryptoJS.enc.Base64).replace(/=+$/, '').replace(/\//g, '_').replace(/\+/g, '-'); // crypto-js doesn't have base64url encoding; we must manually make the tokens URL safe
  let signatureRefreshArray = CryptoJS.HmacSHA256(tokenBase + '.' + tokenRefresh, secretKey);
  let signatureRefresh = signatureRefreshArray.toString(CryptoJS.enc.Base64).replace(/=+$/, '').replace(/\//g, '_').replace(/\+/g, '-'); // crypto-js doesn't have base64url encoding; we must manually make the tokens URL safe

  return {tokenRefresh: tokenBase + '.' + tokenRefresh + '.' + signatureRefresh, tokenAccess: tokenBase + '.' + tokenAccess + '.' + signatureAccess};
}

// you may also need this in your ember-cli-build:
app.import('node_modules/crypto-js/crypto-js.js', {
  using: [
    { transformation: 'amd', as: 'CryptoJS' }
  ]
});

This fn lives in our mirage/config.js file, above the export default function() { opening module line so it can be called by any route in the config file: let tokens = generateTokens('thisisnotarealsecretkey');

It returns an object with an "access" token and a "refresh" token, the two token types required by our django jwt setup. Customize the tokenObjBase, tokenObjAccess and tokenObjRefresh to meet your backend's setup.

The basic structure of a jwt token can be found here: https://jwt.io/

To summarize, a jwt token has three strings, separated by two periods (.).

The first string is the tokenObjBase passed through JSON.stringify(), then converted to a base64URL value. That URL part is important, because regular base64 encodings don't remove the =, + and / chars, which are not "web safe." The tokenObjBase must contain typ and alg properties and nothing else.

The second string is your "payload" (here, tokenObjAccess or tokenObjRefresh) and usually contains user info (name, id, etc), and also an epoch date value which represents the expiration date of the token. That payload obj, like the first, is passed through JSON.stringify(), then converted to a base64URL value. DO NOT put sensitive data in these first two objs, they are not "encrypted" at all. Base64 encoding can be reversed by anyone with a computer and Google.

The third string is the jwt "signature." It is created by concatenating the first two base64 strings with a period (.) in the middle, then passing them through the HS256 encryption algorithm (HMAC-SHA256).

Then all three strings (two base64URL strings and the HS256 encrypted string) are concatenated: base64URL(tokenObjBase) + '.' + base64URL(tokenObjPayload) + '.' + signatureHS256

Hope this helps anyone having issues with jwt permanently logging their mirage users out of their Ember applications!




Why is broccoli-sass-source-maps looking in the wrong directory for my SCSS file?

I'm using broccoli-sass-source-maps with an Ember 2.18.2 application. (In the process of upgrading from an even older version of Ember.js). When I try to build the application, I get this error:

Build failed.
Build Error (Funnel)

ENOENT: no such file or directory, lstat '/[PROJECT HOME DIR]/tmp/funnel-input_base_path-jVWRZW6Y.tmp/images/styles/temporary.scss'

The actual location of the file is /[PROJECT HOME DIR]/app/underway/styles/temporary.scss. Therefore, in our ember-cli-build.js file, we have configuration like this (I've removed a lot of stuff which seems unrelated to me):

let compileSass = require('broccoli-sass-source-maps')(require('sass'));
let mergeTrees = require('broccoli-merge-trees');

let underwayCss = compileSass(['app/underway/styles'],
  'temporary.scss',
  'assets/temporary.css');

// Merging all the assets together to be served
let assets = mergeTrees([
  underwayCss,
  // output of several other trees
], {
  overwrite: true
});

return app.toTree(assets);

Why is the compileSass() method trying to find the temporary.scss file in an images/styles directory?




Cannot filter my transactions by the current user - Ember JS

So I am trying to filter my transactions by the selectedUser. I am not using sessions for the user system, instead I use a menu that updates selectedAt and I take the last selected user this way. Now I want to show the transactions only from the selected user. I've tried multple variants but they don't seem to work for me.

My controller looks like this

users: computed(function() {
    return this.get('store').peekAll('user');
  }),

  selectedUser: computed('users.length', function() {
    return this.get('users').sortBy('selectedAt').reverse().objectAt(0);
  }),

  transactions: computed(function() {
    return this.get('store').findAll('transaction');
  }),

My transaction model:

export default Model.extend({
  category: DS.attr(),
  name: DS.attr(),
  description: DS.attr(),
  amount: DS.attr(),
  date: DS.attr(),
  typeOfT: DS.attr(),
  user: DS.belongsTo('user')
});

and my User model:

export default Model.extend({
  fullName: DS.attr(),
  picture: DS.attr(),
  darkMode: DS.attr(),
  selectedAt: DS.attr('date'),

  transactions: DS.hasMany('transaction')
});

I can succesfully call each transaction for currentUser in the template by calling them like


  




mercredi 15 janvier 2020

How do I manipulate layer text when using ember font-awesome?

I'm using the official ember font-awesome library and I'm trying to add some text to an icon with the following code:

  <span class="fa-layers fa-lg">
    <FaIcon @icon="circle" @size="3x" />
    <span class="fa-layers-text  fa-inverse" data-fa-transform="shrink-8">
      27
    </span>
  </span>

From what I can see on the documentation examples that should work but no value in the data-fa-transform attribute produces any change.

Is there a different method I need to use because FA now uses SVGs?




Correct way to use actions with ember-bootstrap

Created a new ember octane app (3.15) and using ember-bootstrap with it. I am using a modal like so

<BsModalSimple
  @open=true
  @title="Create new podcast"
  @closeTitle="Cancel"
  @submitTitle="Create"
  @size="lg"
  @closeButton=false
  @fade=false
  @backdrop=true
  @backdropClose=false
  @renderInPlace=false
  @onHidden=
  @position="center">
</BsModalSimple>

This works but I get an error which says

Do not use action as . Instead, use the on modifier and fn helper.

What's the right way to use an action in this scenario? I've tried this but it didn't work





State Management in Ember application

I am trying to compare state management solution which is present in ReactJS (using Redux or Context API/Hooks) and trying to identify a somewhat comparable thing in an Ember application.

Can Ember services (being a singleton) be termed as the state management solution in Ember application OR is there something else which can be used for state management in an Ember app ?




mardi 14 janvier 2020

Ember.Js Using TransitionTo Route with dynamic segment

I have an ember application (version 3.14) which I'd like to do a transition to a Route with dynamic segment

I'd like to redirect to /projects/other/2020 when user visits /projects/other I change my projects/other route so it looks like this but it throws me an error

import Route from '@ember/routing/route';

export default Route.extend({

    model: function(){

    },
    redirect() {
        let year_data = {
            year: '2020'
        };
        this.transitionTo('projects.other',year_data);
    }
});

and this is how my projects route looks like in routes.js

this.route('projects', function() {
  this.route('notable',{path: '/'});
  this.route('other', function() {
    this.route('list', {path: '/:year'});
  });
});

these are the errors from google chrome console box

error screenshot




lundi 13 janvier 2020

How to pass an "action" from a template to it's grand child components in Ember Octane

I am trying to pass an "action" from the controller to the grandchild component of the current template. But it fails for somereason. Could anyone let me know what am I missing here.

MainTemplate's Router Controller

export default class MainTemplateController extends Controller {

  field = "userId";

  @action
  save () {
    //save data
  }

}

MainTemplate.hbs

<ChildComponent @field= @save= /> 


ChildComponent.hbs 

<GrandChildComponent @field= @save= />


GrandChildComponent.hbs

<button @onClick=>Save</button>

export default class GrandChildComponent extends Component {    
    @action
    doSomething(fieldName) {
        console.log(fieldName); // logs as "userId"
        console.log(this.args.save) // undefined
    }    
}



vendredi 10 janvier 2020

Copy/Passthrough css file with ember-cli-sass

I'm using ember-cli-sass with my ember app. Now I have a css file in the app/styles directory that I'd like to be copied to dist/assets (preferably minified but not necessary).

I've tried this in the build pipeline which gives a my-file.scss not found error

outputPaths: {
      app: {
        css: {
          'my-file': '/assets/my-file.css',
        }
      }
    }

and this which doesn't do anything

sassOptions: {
      passthrough: {
        include: ['app/styles/my-file.css']
      }
    }



jeudi 9 janvier 2020

How to invoke an action in the current router from the child component in Ember Octane?

I am working with Ember Octane version, I want to invoke an action in the 'router' from the child component. The pseudo code is as follows.

**Router**
export default class SomeRouter extends Route {    
    model() {
        return data;        
    }
    @action
    refreshRoute() {
        this.refresh();
    }
}

**SomerRouter.hbs** 

<ChildComponent> //Using child component here

**ChildComponent**
export default class ChildComponent extends Component { 
    @action
    revert() {
       //How do I invoke the "refreshRoute" on the SomeRouter from here?
    }
}

In the revert method of the above child component, "this" refers to the component itself but in the previous version of the ember "this" refers to the router where I could simply call this.refresh(). So how do I achieve this in Ember Octane. Would really appreciate any help.




mercredi 8 janvier 2020

EmberJS: How to load assets relative to rootURL or load assets using absolute path

this might be a pretty common question but what I found on google does not help me.

I have a emberJs Project with all assets(images, etc) in my-ember-project/public/assets/images/ everything works fine when i load the assets from homepage which is the root URL "/" or localhost:4200

for example in my homepage I have a component with img tag which looks like this

<img src="assets/images/articles/article-1.jpg"/>

on another page with url localhost:4200**/articles/** I also load the same image with the same tag but from what I've seen it tried to load the image from localhost:4200/articles/assets/images/articles/article-1.jpg and not from the correct path localhost:4200/assets/images/articles/article-1.jpg

adding "/" before "assets/images/" works for me if I'm trying to host my project on root folder but when I need to host my project on subdirectory so my url (https://ift.tt/2t2jegV)

how do I load my assets from absolute path or relative to my settings of rootURL adding seems to do nothing to me




Sinon how to stub method for unit testing a Async function

I am trying to write a unit test for an async function using mocha and sinon.js

Below is my test case

  describe('getOperations', function () {
    let customObj, store, someObj
    beforeEach(function () {
      someObj = {
        id: '-2462813529277062688'
      }
      store = {
        peekRecord: sandbox.stub().returns(someObj)
      }
    })
    it('should be contain obj and its ID', function () {
      const obj = getOperations(customObj, store)
      expect(obj).to.eql(someObj)
    })
  })

Below is the definition of the async function I am testing.

async function getOperations (customObj, store) {
  const obj = foo(topLevelcustomObj, store)
  return obj
}

function foo (topLevelcustomObj, store) {
    return store.peekRecord('obj', 12345)
}

The test case fails as the promise being return is rejected with a message

TypeError: store.query is not a function at Object._callee$.

The code I am testing is not calling store.query anywhere and also I have stubbed store.peekRecord also so not sure how it is getting called.




mardi 7 janvier 2020

ember sass import file with tilde

I'm trying to import in an ember project that uses ember-cli-sass a scss file from a node_package which imports another scss file from another node package using ~;

basically the file I'm importing contains the following instruction:

@import "~bootstrap/scss/functions"; // from bootstrap node_module

but that breaks the build since it seems that ember-cli is not resolving the ~;

I've configured ember-cli-build with

sassOptions: {
  includePaths: [
    'node_modules/<package_name>/scss',
  ]
},



lundi 6 janvier 2020

error find-up@4.1.0: The engine "node" is incompatible with this module. Expected version ">=8". Ember js + Heroku Deployment

  • Ember-CLI:- 3.4.3
  • Node:- 6.9.5
  • Yarn:- 1.9.4

During the deployment of my ember project on Heroku, I got this error here is log. We have find-up version 3.0.0 but during deployment, it is still trying to download find-up@4.1.0 if anyone have an idea about this to ignore download of the latest version of find-up or any solution so comment it here it will be very helpful thanks in advance.

error find-up@4.1.0: The engine "node" is incompatible with this module. Expected version ">=8".
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
 !     Push rejected, failed to compile Ember CLI app.
 !     Push failed

Here is my Package.json

   {
  "name": "tabsys-client",
  "version": "2.13.1",
  "private": true,
  "description": "Web and mobile client for Activate Universal",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "lint:js": "eslint ./*.js app config lib server tests",
    "start": "ember serve",
    "test": "ember test",
    "postinstall": "node -e \"try { require('fs').symlinkSync(require('path').resolve('node_modules/@bower_components'), 'bower_components', 'junction') } catch (e) { }\""
  },
  "dependencies": {
    "@bower_components/FakeXMLHttpRequest": "trek/FakeXMLHttpRequest#^1.4.0",
    "@bower_components/Faker": "Marak/Faker.js#~3.1.0",
    "@bower_components/d3": "mbostock-bower/d3-bower#^4.11.0",
    "@bower_components/d3-tip": "Caged/d3-tip#^0.7.1",
    "@bower_components/dexie": "dfahlander/dexie.js#^2.0.0-beta.11",
    "@bower_components/dialog-polyfill": "GoogleChrome/dialog-polyfill#^0.4.7",
    "@bower_components/ember-qunit-notifications": "dockyard/ember-qunit-notifications#0.1.0",
    "@bower_components/highcharts-custom-events": "blacklabel/custom_events#2.1.4",
    "@bower_components/leaflet": "Leaflet/Leaflet#^1.0.0",
    "@bower_components/material-design-lite": "google/material-design-lite#^1.2.1",
    "@bower_components/pretender": "trek/pretender#~1.1.0",
    "@bower_components/qunit-notifications": "dockyard/qunit-notifications#~0.1.0",
    "@bower_components/route-recognizer": "tildeio/route-recognizer#~0.1.1",
    "@bower_components/sauce-material-design": "sauce-consultants/sauce-material-design#1.0.0rc8",
    "ember-cli": "^3.4.3",
    "object.values": "^1.0.4",
    "replace": "^1.1.1"
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "broccoli-funnel": "2.0.1",
    "corber": "1.3.10",
    "ember-ajax": "^3.0.0",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^7.1.2",
    "ember-cli-clock": "2.1.1",
    "ember-cli-dotenv": "^2.0.0",
    "ember-cli-eslint": "^4.2.1",
    "ember-cli-fastclick": "1.3.0",
    "ember-cli-favicon": "1.0.0-beta.4",
    "ember-cli-geo": "^4.0.0",
    "ember-cli-htmlbars": "^2.0.3",
    "ember-cli-htmlbars-inline-precompile": "^1.0.2",
    "ember-cli-inject-live-reload": "^1.8.2",
    "ember-cli-moment-shim": "3.3.1",
    "ember-cli-nouislider": "^0.14.1",
    "ember-cli-qunit": "^4.1.1",
    "ember-cli-release": "^1.0.0-beta.2",
    "ember-cli-sass": "7.1.3",
    "ember-cli-shims": "^1.2.0",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-uglify": "^2.0.0",
    "ember-composability": "0.3.7",
    "ember-concurrency": "0.7.17",
    "ember-cordova-events": "0.1.0",
    "ember-cordova-platform": "^0.1.0",
    "ember-cordova-splash": "0.1.4",
    "ember-crumbly": "2.0.0-alpha.1",
    "ember-data": "~2.18.0",
    "ember-data-url-templates": "0.2.0",
    "ember-drag-drop": "^0.6.2",
    "ember-export-application-global": "^2.0.0",
    "ember-file-upload": "2.0.0-beta.24",
    "ember-highcharts": "0.5.4",
    "ember-i18n": "5.0.2",
    "ember-inflector": "2.0.1",
    "ember-leaflet": "3.0.9",
    "ember-load-initializers": "^1.0.0",
    "ember-local-storage": "^1.4.0",
    "ember-lodash": "^4.17.5",
    "ember-material-lite": "0.2.5",
    "ember-md5": "^1.2.0",
    "ember-modal-dialog": "^2.4.1",
    "ember-moment": "7.0.0-beta.3",
    "ember-new-computed": "1.0.3",
    "ember-pikaday": "2.2.2",
    "ember-power-select": "1.9.6",
    "ember-radio-button": "1.0.7",
    "ember-resolver": "^4.0.0",
    "ember-route-action-helper": "2.0.6",
    "ember-sauce-material-design": "sauce-consultants/ember-sauce-material-design.git#1.0.0rc18",
    "ember-sauce-toolkit": "sauce-consultants/ember-sauce-toolkit#0.1.5",
    "ember-select-box": "1.1.14",
    "ember-service-worker": "0.6.6",
    "ember-service-worker-asset-cache": "0.6.1",
    "ember-service-worker-index": "0.6.1",
    "ember-sortable": "1.9.3",
    "ember-source": "~2.18.0",
    "ember-tether": "^1.0.0-beta.0",
    "ember-truth-helpers": "2.0.0",
    "ember-web-app": "^2.0.0",
    "ember-welcome-page": "^3.0.0",
    "emberx-file-input": "^1.1.2",
    "eslint-plugin-ember": "^5.0.0",
    "highcharts": "^7.0.0",
    "liquid-fire": "0.27.3",
    "loader.js": "^4.5.0",
    "pikaday": "1.6.1",
    "smd-colors": "sauce-consultants/smd-colors.git#25e787d8a85af98c60ec3482e0534ea8aaab1208",
    "torii": "0.9.3"
  },
  "engines": {
    "node": "6.9.5",
    "yarn": "1.9.4"
  }
}



Ember JS Router - How to produce a 404 Http response code for error page

I'm getting this error when running a SEO audition tool

enter image description here

I would need to produce something similar to:

enter image description here

Instead of 404 my error page has a 200 status.




vendredi 3 janvier 2020

New Ember.js app in shared folder of VMware Ubuntu guest

I am trying to develop an Ember.js app in VMware. The scenario is the following:

  • Host: Windows 7 Pro.
  • Guest: Ubuntu Server 18.04.

After installation of Ember.js, "ember -v" returns:

ember-cli: 3.15.1
node: 12.14.0
os: linux x64

If i try to create a new Ember app from my home directory there is no problem but, as I want to edit files from Windows host OS, when I try to do the same (ember new app_name) in the shared folder (/mnt/hgfs/folder_name/) an error is thrown:

Error creating new application. Removing generated directory `./app_name`
Command failed: npm install --loglevel error
npm WARN deprecated core-js@2.4.1: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated exists-sync@0.0.4: Please replace with usage of fs.existsSync
npm ERR! code ENOENT
npm ERR! syscall rename
npm ERR! path /mnt/hgfs/folder_name/app_name/node_modules/.acorn-dynamic-import.DELETE/node_modules/acorn
npm ERR! dest /mnt/hgfs/folder_name/app_name/node_modules/acorn-dynamic-import/node_modules/acorn
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, rename '/mnt/hgfs/folder_name/app_name/node_modules/.acorn-dynamic-import.DELETE/node_modules/acorn' -> '/mnt/hgfs/folder_name/app_name/node_modules/acorn-dynamic-import/node_modules/acorn'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/user/.npm/_logs/2020-01-03T21_43_21_623Z-debug.log


Stack Trace and Error Report: /tmp/error.dump.1e44562d410bb23303e1023cf42f30f8.log

I tried the following solution from https://docs.npmjs.com/getting-started/fixing-npm-permissions

# Make a directory for global installations:
mkdir ~/.npm-global

# Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'

#Open or create a ~/.profile file and add this line:
export PATH=~/.npm-global/bin:$PATH

#Back on the command line, update your system variables:
source ~/.profile

But no success.

Any help would be appreciated to solve this issue.




jeudi 2 janvier 2020

Store Rails Json response in ember

I am working on authentication of a user .

currently i am posting a session with username and password . which will be sent to rails bcrypt for authentication ,if authentication is true then this will return a json of user object .

how will i grab this user in ember so that i can store it in my service .

Login Function :

login(user) {
    console.log("this is working ")

    //this.get('sessionaccount').login(user)

    this.store.createRecord('session', {
        email: this.currentModel.email,
        password: this.currentModel.password
    }).save().then(function(data) {
        console.log(data.id) 
        this.id = data.id
        this.get('sessionaccount').login(data)
    });
}