首页 > 解决方案 > 将mysql值从节点js传递到角度

问题描述

嗨,我有这个 post 函数来调用创建函数,该函数将插入数据库

router.post('/', async (req, res, next) =>
{
	const body = req.body;
	console.log("tu sam todo_task",req.body);

	try
	{
		const todo_task = await TodoTaskService.create(body);
		console.log(todo_task, "function")

		// created the todo_task! 
		return res.status(201).json({ todo_task: todo_task });
	}
	catch(err)
	{
		
	}
});

然后在第二个片段中,我在服务类中有这个创建函数,我想从 mysql 查询返回结果

class TodoTaskService
{
	static create(data)
	{
		console.log("tu sam service todo_task create");
		var vres = todoTaskValidator.validate(data, todo_taskVSchema);
		
		/* validation failed */
		if(!(vres === true))
		{
			let errors = {}, item;

			for(const index in vres)
			{
				item = vres[index];

				errors[item.field] = item.message;
			}
			
			throw {
			    name: "ValidationError",
			    message: errors
			};
		} 
		console.log("tu sam service todo_task validation passed");
		let todo_task = new TodoTaskModel(data.todo_task_name, data.todo_task_complete_f);



		let connection = mysql.createConnection(dev);

		// insert statment
		let sql = `INSERT INTO todo_task (todo_task_name,todo_task_complete_f) VALUES (?);`
		let values = [data.todo_task_name, data.todo_task_complete_f];


		// execute the insert statment
		 connection.query(sql, [values], (err, results, fields) => {
			if (err) {
				global.query = "Database error";
				console.log(err.message + "zasto");
				return err
				
			}
			else{
				// get inserted rows
				global.query = "OK";
				todo_task.todo_task_id = results.insertId
				console.log("rows inserted",todo_task);
				return todo_task;
			}
		}); 
	}

	

	
}

如何将 return todo_task 从 connection.query 传递回第一个 post 函数并将其发送到 angular?

标签: node.js

解决方案


我自己找到了一个解决方案,不知道这是否是最佳实践,但这是我的解决方案,我正在使用回调来传递值

    router.post('/', async (req, res, next) =>
{
    const body = req.body;
    try
    {
        return await TodoTaskService.create(body,function (result){
            console.log(result, "function result")
            todo_task = result;
            return res.status(201).json({ todo_task: todo_task });
        });


        // created the todo_task! 
        //return res.status(201).json({ todo_task: todo_task });
    }

返回带有结果的回调

class TodoTaskService
{
    static create(data,callback)
    {
        var vres = todoTaskValidator.validate(data, todo_taskVSchema);

        /* validation failed */
        if(!(vres === true))
        {
            let errors = {}, item;

            for(const index in vres)
            {
                item = vres[index];

                errors[item.field] = item.message;
            }

            throw {
                name: "ValidationError",
                message: errors
            };
        } 
        console.log("tu sam service todo_task validation passed");
        let todo_task = new TodoTaskModel(data.todo_task_name, data.todo_task_complete_f);

        /* todo_task.uid = 'c' + counter++;

        todo_tasks[todo_task.uid] = todo_task; */

        let connection = mysql.createConnection(dev);

        // insert statment
        let sql = `INSERT INTO todo_task (todo_task_name,todo_task_complete_f) VALUES (?);`
        let values = [data.todo_task_name, data.todo_task_complete_f];


        // execute the insert statment
        connection.query(sql, [values], (err, results, fields) => {
            if (err) {
                global.query = "Database error";
                console.log(err.message + "zasto");
                return err

            }
            else{
                // get inserted rows
                global.query = "OK";
                todo_task.todo_task_id = results.insertId
                console.log("rows inserted",todo_task);
                return callback(todo_task);
            }
        }); 
    }

推荐阅读