dimanche 7 mars 2021

Uncaught type error: Cannot read property 'ajax' of undefined

I'm new to ember.js and this is my first application. I want to build a login form in which if the user has passed in the right email and password, he should be transitioned to the home page. I am not sure whether I should use Ember Data for the login part but I read somewhere that Ember Data is not suitable for this specific login task so I should make ajax request (Is this assumption right ?). However, when I made the request I received the following error :

Uncaught type error: Cannot read property 'ajax' of undefined at LoginComponent.logUser

I have made the http request in a login component class but I am not sure whether I should use a controller for this part as in all the examples I have seen the request was handled in controllers. However, I do not know how to use the login controller on a click on the login button.

So I have a few more questions apart from how to handle the error that I have:

  1. Should I use Ember Data (if yes how) for the login task or should I use the ajax method?
  2. What is the difference between a controller and component(the class) and when I should use each of them user clicks on handling data or making request as in this case?

Thank you in advance for your help!

Here is my code

login.hbs - template:

<h1 id="pageTitle">Log In</h1>
<Login/>

login.hbs - component:

<form  id="login">
    <label class='formElement labelLogin'>Email :</label><br>
    <Input class='formElement input' @value=/><br>
    <label class='formElement labelLogin'>Password :</label><br>
    <Input class='formElement input' @value=/><br>
    <button id="loginButton" class='button formElement' type="submit">Log In</button> 
</form>

login.js - component class

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

export default class LoginComponent extends Component{
  @tracked email;
  @tracked password;

  @action
  logUser(){
        let userData = JSON.stringify({
            'email' : this.email,
            'password' : this.password
        });
        Ember.$.ajax({
            url : 'https://gara6.bg/auto-api/users/login',
            type : 'POST',
            dataType: 'json',
            data : userData,
        }).then(() => {
            alert('Logged In');
            this.transitionToRoute('home');
        }).catch(function(error){
            alert(`Error: ${error}`);
        });
    }
}

routes.js:

import EmberRouter from '@ember/routing/router';
import config from 'gara6/config/environment';

export default class Router extends EmberRouter {
  location = config.locationType;
  rootURL = config.rootURL;
}

Router.map(function () {
  this.route('login');
  this.route('home');
});
  



Aucun commentaire:

Enregistrer un commentaire