角度-错误TypeError:_co.timeIn不是函数

时间:2018-07-20 04:31:35

标签: javascript mysql node.js angular typeerror

我正在使用Angular,Express,Node.js和MySQL创建一个项目。我在HTML上做了一个按钮,它将调用一个函数,该函数实际上会将当前时间插入到我的MySQL数据库中,并将插入的时间返回给HTML。我的功能第一次完全起作用。以下是与该问题相关的代码:

component.html:

<tr *ngFor='let student of allStudents'>
            <td>{{student.student_id}}</td>
            <td>{{student.first_name}}</td>
            <td>{{student.last_name}}</td>
            <td *ngIf='!student.time_in'><input type="button" name="" (click)='timeIn(student.student_id)' value="">NULL</td>
            <td *ngIf='student.time_in'>{{student.time_in}}</td>
</tr>

component.ts

timeIn(val){
    val = {'val': val}
    return this._api.timeIn(val)
    .then(data => this.timeIn = data)
    .catch(errors => { console.log(errors)})
}

service.ts

timeIn(id){
    return this._http.post('/timeIn', id)
    .map(data => data.json())
    .toPromise();
}

controller.js

timeIn: function(req, res){
        connection.query('UPDATE students SET time_in = NOW() WHERE student_id = ' + req.body.val + ';', function(err, results, fields){
            if (err) console.log(err.message);
            connection.query('SELECT student_id, time_in FROM students WHERE student_id = ' + req.body.val + ';', function(err, results, fields){
                if (err) console.log(err.message);
                console.log(results);
                res.send(results);
            })
        })
    }

Console.log(结果)

[ RowDataPacket { student_id: 45678, time_in: 2018-07-20T04:17:42.000Z } ]

您可以看到,数据库中为每个学生创建了多个按钮。每个人都有其自己的按钮以及其唯一的student_id。但是,单击第一个按钮后,它将不再起作用。第一次执行 time_in()时,将更新并返回当前时间。但是,此功能以后将不再起作用。在HTML控制台中,它返回以下错误:

StudentdashboardComponent.html:29 ERROR TypeError: _co.timeIn is not a function
at Object.eval [as handleEvent] (StudentdashboardComponent.html:29)
at handleEvent (core.js:13589)
at callWithDebugContext (core.js:15098)
at Object.debugHandleEvent [as handleEvent] (core.js:14685)
at dispatchEvent (core.js:10004)
at core.js:10629
at HTMLInputElement.<anonymous> (platform-browser.js:2628)
at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4751)
at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)

如果刷新页面,则可以再次调用该函数,但是每次刷新最多只能使用一次。有谁知道为什么第二通电话后它不起作用?我找不到与我的问题有关的任何东西,因此将不胜感激。

1 个答案:

答案 0 :(得分:1)

似乎在组件中,您已经将timeIn声明为函数和变量。

因此,由于该角度是可变的还是函数的,它变得令人困惑。尝试更改您的变量名。

下面的this.timeIn = data是什么?

timeIn(val){
    val = {'val': val}
    return this._api.timeIn(val)
    .then(data => this.timeIn = data) // what is this timeIn ??????
    .catch(errors => { console.log(errors)})
}

注意:

  

我可以再次调用该函数,但是每个函数最多只能调用一次   刷新

之所以发生这种情况,是因为您的timeIn第一次可以毫无问题地识别为一个函数。但是在timeIn函数内部,您正在将data的{​​{1}}分配给this._api.timeIn,在这种情况下,timeIn不再被视为函数,而是被认为是timeIn具有的类型。这就是为什么您得到 data 的原因。使用其他变量来分配timeIn is not a function

感谢@coder编辑我的答案:)