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

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

我是 ember.js 的新手,这是我的第一个应用程序。我想建立一个登录表单,如果用户输入了正确的电子邮件和密码,他应该被转换到主页。我不确定我是否应该使用 Ember 数据作为登录部分,但我在某处读到 Ember 数据不适合这个特定的登录任务,所以我应该提出 ajax 请求(这是假设正确吗?)。但是,当我发出请求时,我收到了以下错误:

未捕获的类型错误:无法读取 LoginComponent.logUser

处未定义的 属性 'ajax'

我已经在登录组件中发出了 http 请求 class 但我不确定是否应该为此部分使用控制器,因为在我看到的所有示例中,请求都是在控制器中处理的。但是,我不知道如何在单击登录按钮时使用登录控制器。

所以除了如何处理我遇到的错误之外,我还有几个问题:

  1. 我应该使用 Ember 数据(如果是如何)进行登录任务还是应该使用 ajax 方法?
  2. 控制器和组件(class)之间有什么区别,我应该在什么时候使用它们中的每一个,用户点击处理数据或发出请求,就像在这种情况下一样?

提前感谢您的帮助!

这是我的代码

login.hbs - 模板:

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

login.hbs - 组件:

<form {{on "submit" this.logUser}} id="login">
    <label class='formElement labelLogin'>Email :</label><br>
    <Input class='formElement input' @value={{this.email}}/><br>
    <label class='formElement labelLogin'>Password :</label><br>
    <Input class='formElement input' @value={{this.password}}/><br>
    <button id="loginButton" class='button formElement' type="submit">Log In</button> 
</form>

login.js - 组件 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');
});
  

这是使用 fetch 编辑的 login.js 组件 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 = {
            'email' : this.email,
            'password' : this.password
        };
        let fetchObject = {
            method: 'POST',
            headers : {
                'Content-type' : 'application/json', 
            },
            body : JSON.stringify(userData),
        };
        fetch('https://gara6.bg/auto-api/users/login',fetchObject)
        .then(response => {
            alert(response.status);
            alert(response.statusText);
            if(!response.ok){
                alert('Network response was not ok');
            }
            alert(response.json());
            return response.json();
            // alert('Logged In');
            // this.transitionToRoute('home');
        }).then(data =>{
            alert(data);
        }).catch(error => {
            alert(`There has been a problem with your fetch operation: ${error}`);//This is the only alert that shows up.
        });
        console.log(userData);
    }
}

Here I have clicked on the button and the alert shows up

2:This is the request data for the red login request. Surprisingly, there is request payload which matches the content of my text fields

Here is what is shown when I click OK on the alert. The number of requests have changed

This is the request data for the newly shown login request (note his type is GET)

于是在朋友的帮助下,POST请求转为GET的问题已经解决了。事实证明问题出在表单元素上,默认情况下它具有预定义的函数,因此解决方案是使用 e.preventDefault().

来阻止它们

这是已经可以运行的代码:

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

export default class LoginComponent extends Component{
  @tracked email;
  @tracked password;
  @service router;
  
  @action
  logRequest(){
    let result=0;
    let userData = {
        'email' : this.email,
        'password' : this.password
    };
    let fetchObject = {
        method: 'POST',
        headers : {
            'Content-type' : 'application/json', 
        },
        body : JSON.stringify(userData),
    };
    fetch('https://gara6.bg/auto-api/users/login',fetchObject)
        .then(response => {
            if(!response.ok){
                throw new Error('Network response was not ok');
            }
            result=1;
        })
        .catch(error => {
            alert(`There has been a problem with your fetch operation: ${error}`);
        });
    return result;
  }


  @action
  logUser(e){
    e.preventDefault();
        let result = this.logRequest;
        if(result){
            alert('Logged in');
            this.router.transitionTo('home');
        }
        else{
            alert('Not logged in');
        }
    }
}