samedi 30 avril 2022

EmberJS model from route returns undefined in controller

Can some one help me on the below doubt?

I am using EmberJS 3.4 version and I have a route which looks like

export default Route.extend({
model(){
    const items = [{price: 10}, {price: 15}]
    return items
 },
});

and a controller which returns undefined for model

export default Controller.extend({

    init(){
        console.log(this.model); //returns undefined
        console.log(this); //has the model object as a property
    },
  })

see this image which contains output

For some reason, this.model returns undefined but when I log "this", it has the model object as the property listed.

My question is, when I access model within a computed property why the property isn't undefined ?

export default Controller.extend({

subtotal: computed('this.model', function(){
     return  this.model.reduce((acc, item) => {
         return acc + item.price
     },0) // return 25
    }),
 })



vendredi 29 avril 2022

how to reduce dependency size on ember

I am trying to reduce monaco-editor dependency size.
I found this answer which shows how to do it on angular - by editing the glob configuration in angular.json file.
What is the corresponding file for this configuration on ember?




jeudi 21 avril 2022

How can I connect my ember app to servlet runnning on tomcat

I am new to ember,so I have created a servlet to continuously read a log file and have created a component in ember for front end (I have build the emberapp and added it to the webapps in servlet package in tomcat.But I am able to see only html page in my server and when i click enter no response are there in the browser.

filetail.js

import Component from '@glimmer/component';
import {action} from '@ember/object';

export default class FiletailComponent extends Component {
    @action
    tailfile() {
        let filepath = document.getElementById("filepath").value;
        
        $.ajax({
            type: "GET",
      
            url: "/sre",//servlet url
            data: {

                filepath: filepath
            },
            dataType: "text",
            success: function (data) {
                document.getElementById('tail').innerHTML += data;           
            },
            error: function (jqXHR, testStatus, errorThrown) {
                console.log("error thrown: " + testStatus);
            }
            
        });
        
    }
}

filetail.hbs

<form>
    <input type="text" id="filepath" required >
    <label>filepath:</label>
    <input  type="submit" value="Enter">
    <div id="tail"></div>
</form>

sre.java


@WebServlet("/sre")
public class sre extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/plain");  
        PrintWriter printwriter = response.getWriter();
        
        String path=request.getParameter("filepath");
        
        System.out.println("path is "+path);
        File file= new File(path);
        if(!file.exists()) {
            printwriter.println("file doesnot exist");
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        long length = randomAccessFile.length();
        String temp;
        int foundLine = 0;
        while (length > 0 && foundLine < 10) {
            randomAccessFile.seek(length--);
            if (randomAccessFile.read() == 10) {
                foundLine++;
            }
        }
        while((temp = randomAccessFile.readLine()) != null) 
        {
            printwriter.println(temp);              

        }
        response.flushBuffer();
        
        String parentFolder = file.getParent()+"/";
        Path filepath = Paths.get(parentFolder);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        WatchKey wk = filepath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        try 
        {
            while(true){
                wk = watchService.take();
                for (WatchEvent<?> event : wk.pollEvents()) {
                    Path changed = (Path) event.context();
                    if(changed.endsWith(file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/")+1))){
                        while((temp = randomAccessFile.readLine())!=null) {
                            printwriter.println(temp);              
                        }
                        response.flushBuffer();  
                    }

                }
                boolean valid = wk.reset();
                if (!valid) 
                    break;
            }
        }

        catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

In short I need to get the file path from the user using emberfor frontend and then pass the filepath to the servlet and then print the contents in file in browser...Any help would be great




dimanche 17 avril 2022

Errors when using "npm start" (in MacOS)

I have been trying for sometime already to just run "npm start" for an old app developed with EmberJs but I get several errors. I had tried the following:

  1. Uninstall, cache clean, install Ember-cli
  2. Remove the "node_modules" and run "npm install"
  3. Updating ember-cli-babel
  4. And some few others like updating / removing packages

I haven't open this project for around 3 years so I am pretty sure there are new updates that probably I need to follow but not sure what else to do after the list I just mentioned above.

I uploaded what I get when running "npm start". Any guidance, help, or suggestion I would appreciate it! Thanks in advance!!

user@User-MacBook-Air app2 % npm start                         

> app@0.0.0 start /Users/user/Projects/app2
> ember serve

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: app -> ember-clean-tmp -> ember-cli-babel
ember-cli-htmlbars-inline-precompile v1.0.0 and above require the ember-cli-babel v6.7.1 or above. To use ember-cli-babel v5.x please downgrade ember-cli-htmlbars-inline-precompile to v0.3.

An error occurred in the constructor for ember-cli-htmlbars-inline-precompile at /Users/user/Projects/app2/node_modules/ember-cli-htmlbars-inline-precompile

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! app@0.0.0 start: `ember serve`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the app@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/user/.npm/_logs/2022-04-17T17_03_00_039Z-debug.log



vendredi 15 avril 2022

How to highlight the selected item from basic dropdownlist in ember?

I'm using a basic dropdown in Ember and in the list, once we select item in the content list, I want to highlight the selected item. I'd like to know if I can use a simple [aria-current] & [aria-selected] in CSS to make it happen.

hbs file:

 
   <li class=" dropdown-class" >
        <p </p>
    </li>




jeudi 14 avril 2022

Append to Ember Rails component?

As a discourse plugin, how can I append to an ember component?

plugins/myplugin/plugin.rb

after_initialize do
  add_to_serializer(:topic, :myplugin_method) do
    # object...
  end
end



How to modify/change the ember mirage response in my tests file?

The application uses ember-cli-mirage to mock the data and uses specific endpoint to get the specific response. Mocking data and showing the content to the templates works fine.

Problem: I can't modify the response of this endpoint GET /foos in my test file.

/mirage/config.js

export default function () {
  this.namespace = '/api';

  let foos = {
    foos: [
      {
        id: 1,
        name: 'foo-2',
        description: 'foo description'
      },
    ],
  };

  this.get('/foos', function () {
    return foos;
  });
}

tests/acceptance/foo-test.js

import { module, test } from 'qunit';
import { visit, currentURL, click, find, findAll } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';

module('Acceptance | foo', function (hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  test('visiting /foo', async function (assert) {
    this.server.get('/foos', () => {
      return new Response(
        200,
        {
          foos: [
            {
              id: 20,
              name: 'foo-3'
            }
          ]
        },
      );
    })

    await visit('/foo');
    assert.equal(currentURL(), '/foo');
  });
});

Question: How to modify the response of this endpoint GET /foos inside my test file? I want my test file to have a different response




mardi 12 avril 2022

Content-Disposition: download file automatically

The API call to the server is returning a zip file with Content-Disposition in format attachment, <filename> I am using FileSaver's saveAs to save the file.

    this.ajax.raw(requestUrl, {
        dataType: 'binary',
        xhr: () => {
          const myXhr = $.ajaxSettings.xhr()
          myXhr.responseType = 'blob'
          return myXhr
        }
      }).then((response) => {
        this.downloadSuccess(response, minTimeString, maxTimeString, downloadCompletedMessage)
      }).catch((e) => {
        this.downloadError(e)
      })

downloadSuccess (response, minTime, maxTime, downloadCompletedMessage) {
    const filename = (response.jqXHR.getResponseHeader('Content-Disposition').split('"')[1])
    saveAs(response.payload, filename, 'application/zip')

This works fine for small files but fails if the file is more than 2Gb (The file is downloaded successfully but the saved file is of 1Kb only).

During my research, I saw that browser can download the file without FileSaver if the response has Content-Disposition which is true in my case. But I am not able to figure out how.

Do I need to use request differently?




dimanche 10 avril 2022

Ember app error - Could not find module `undefined/app` imported from `(require)`

I'm able to start my ember app but nothing loads in the screen and I noticed this error in browser console log. Any idea about what could I be missing?

ember serve

WARNING: Node v16.14.2 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js. See https://git.io/v7S5n for details.

Running without permission to symlink will degrade build performance.
See https://cli.emberjs.com/release/appendix/windows/ for details.

File added: "package.json"

Server restarted.

file changed index.js.map

Build successful (8338ms) – Serving on http://localhost:4200/

Slowest Nodes (totalTime >= 5%)                                                                             | Total (avg)
------------------------------------------------------------------------------------------------------------+---------------------------
Babel: @ember/test-helpers (1)                                                                              | 2631ms
Bundler (1)                                                                                                 | 1011ms
BroccoliRollup (6)                                                                                          | 1008ms (168 ms)
ember-auto-import-analyzer (3)                                                                              | 626ms (208 ms)
Package /assets/vendor.js (1)                                                                               | 569ms


Build successful (566ms) – Serving on http://localhost:4200/

Slowest Nodes (totalTime >= 5%)                                                                             | Total (avg)
------------------------------------------------------------------------------------------------------------+---------------------------
Package /assets/vendor.js (1)                                                                               | 79ms
Concat: Vendor Styles/assets/vendor.css (1)                                                                 | 72ms
Funnel (54)                                                                                                 | 42ms (0 ms)

and this is the console error

loader.js:247 
        
       Uncaught Error: Could not find module `undefined/app` imported from `(require)`
    at missingModule (loader.js:247:1)
    at findModule (loader.js:258:1)
    at requireModule (loader.js:24:1)
    at app-boot.js:3:1



samedi 9 avril 2022

Not able to create a new ember app - Could not resolve dependency error

I'm just trying to create a new app from scratch, but getting this error:

Command failed with exit code 1: npm install --loglevel error
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ember-sample@0.0.0
npm ERR! Found: ember-cli@4.3.0
npm ERR! node_modules/ember-cli
npm ERR!   dev ember-cli@"~4.3.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer ember-cli@"~3.2.0" from ember-cli-dependency-checker@3.3.0
npm ERR! node_modules/ember-cli-dependency-checker
npm ERR!   dev ember-cli-dependency-checker@"^3.2.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

These are the repro steps:

open command prompt in Win11. install ember

npm install -g ember-cli

create app ember-sample

ember new ember-sample

and just after that I get the error above.

Could I be missing anything? I have already installed node v16.14.2, npm 8.5.0, ember-cli: 4.3.0 I was already taking a look on ember.js official website




vendredi 8 avril 2022

Setting value from higher in property chain

I'm trying to update a specific value in an object (in Ember 3.12) using the following command:

set(this, 'activeBooking.directDetail.phones.firstObject.number', guestPhone);

This works, but since number isn't the key on a computed, it doesn't update the rendered value on the page, so I'd like to target phones instead, which is the key on a computed. How could I set the number value by hitting phones? Thanks in advance.




Embroider:MacrosConfig the given config from 'Project Path' for packageName 'undefined' is not JSON serializable

When I try to start Ember server (ember serve) I get this error

[Embroider:MacrosConfig] the given config from 'C:\WebDev\cpc\front-end_service\node_modules\ember-get-config' for packageName 'undefined' is not JSON serializable.

Here's the stack error details ;

=================================================================================
    
    ENV Summary:
    
      TIME: Sat Apr 09 2022 01:13:15 GMT+0200 (heure d’été d’Europe centrale)
      TITLE: ember
      ARGV:
      - C:\Program Files\nodejs\node.exe
      - C:\Users\zak\AppData\Roaming\npm\node_modules\ember-cli\bin\ember
      - s
      EXEC_PATH: C:\Program Files\nodejs\node.exe
      TMPDIR: C:\Users\zak\AppData\Local\Temp
      SHELL: null
      PATH:
      - C
      - \Program Files (x86)\AMD APP\bin\x86_64;C
      - \Program Files (x86)\AMD APP\bin\x86;C
      - \Windows\system32;C
      - \Windows;C
      - \Windows\System32\Wbem;C
      - \Windows\System32\WindowsPowerShell\v1.0\;C
      - \Windows\System32\OpenSSH\;C
      - \Program Files\Git\cmd;C
      - \Program Files\dotnet\;C
      - \Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C
      - \Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C
      - \Program Files\nodejs\;C
      - \Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C
      - \Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C
      - \Program Files\PuTTY\;C
      - \Users\zak\AppData\Local\Microsoft\WindowsApps;C
      - \Users\zak\AppData\Local\Programs\Microsoft VS Code\bin;C
      - \Users\zak\AppData\Roaming\npm
      PLATFORM: win32 x64
      FREEMEM: 4299919360
      TOTALMEM: 12786380800
      UPTIME: 60966
      LOADAVG: 0,0,0
      CPUS:
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      - Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz - 2195
      ENDIANNESS: LE
      VERSIONS:
      - ares: 1.17.1
      - brotli: 1.0.9
      - cldr: 39.0
      - icu: 69.1
      - llhttp: 2.1.3
      - modules: 83
      - napi: 8
      - nghttp2: 1.42.0
      - node: 14.17.3
      - openssl: 1.1.1k
      - tz: 2021a
      - unicode: 13.0
      - uv: 1.41.0
      - v8: 8.4.371.23-node.67
      - zlib: 1.2.11
    
    ERROR Summary:
    
      - broccoliBuilderErrorStack: [undefined]
      - code: [undefined]
      - codeFrame: [undefined]
      - errorMessage: [Embroider:MacrosConfig] the given config from 'projectPath\node_modules\ember-get-config' for packageName 'undefined' is not JSON serializable.
      - errorType: [undefined]
      - location:
        - column: [undefined]
        - file: [undefined]
        - line: [undefined]
      - message: [Embroider:MacrosConfig] the given config from 'projectPath\node_modules\ember-get-config' for packageName 'undefined' is not JSON serializable.
      - name: Error
      - nodeAnnotation: [undefined]
      - nodeName: [undefined]
      - originalErrorMessage: [undefined]
      - stack: Error: [Embroider:MacrosConfig] the given config from 'projectPath\node_modules\ember-get-config' for packageName 'undefined' is not JSON serializable.
        at MacrosConfig.internalSetConfig (projectPath\node_modules\@embroider\macros\src\macros-config.js:163:19)
        at MacrosConfig.setOwnConfig (projectPath\node_modules\@embroider\macros\src\macros-config.js:142:21)
        at Class.included (projectPath\node_modules\@embroider\macros\src\ember-addon-main.js:25:26)
        at Class.superWrapper [as included] (projectPath\node_modules\core-object\lib\assign-properties.js:34:20)
        at projectPath\node_modules\ember-cli\lib\models\addon.js:497:26
        at Array.reduce (<anonymous>)
        at Class.eachAddonInvoke (projectPath\node_modules\ember-cli\lib\models\addon.js:494:24)
        at Class.included (projectPath\node_modules\ember-cli\lib\models\addon.js:769:10)
        at Class.superWrapper [as included] (projectPath\node_modules\core-object\lib\assign-properties.js:34:20)
        at Class.included (projectPath\node_modules\ember-get-config\index.js:29:26)
    
    =================================================================================

I searched a lot on Google but I didn't find any solution If someone can help, thanks.




mardi 5 avril 2022

Angular 12 or 13 Observers vs Ember.js

I have been working in Ember.js since last 8 years. Now switched to Angular.js Version 13 In Ember.js if I have to do something when some variables of model change, This was the code

Following code is from Ember.js how can we do the same in Angular.js version 13 or 12

import { observer } from '@ember-cli';
import SomeOtherModel from 'app/models/someothermodel';

foo1:null,
foo2:[],
foo3:false,
SomeOtherModel:someOtherModel

fooObeserver: observer('foo1', 'foo2', 'foo3', 'someOtherModel.foo9', 'someOtherModel.foo12', function(){
      //do bla bla
      this.anymethod();
      this.someOtherModel.anymethod();
      .....
});

Note: fooObserver is not referenceable but whenever these variables will change this block will be executed.