【问题标题】:i want to get response from nodejs to angular 6我想从nodejs得到对angular 6的响应
【发布时间】:2018-12-27 06:24:34
【问题描述】:

如果插入查询成功,我想发送响应消息,否则 nodejs 应该将不成功的消息发送到 Angular 6 并在浏览器上显示 //nodejs文件

exports.create = (req, res) => {
    let uname = req.body.username;
    let mail = req.body.email;


    con.query('SELECT username FROM customers WHERE username = ?', uname,(err,result)=>{

        if(err) throw err;
        con.query('SELECT email FROM customers WHERE email = ?', mail,(err, results) => {
            if(err) throw err;
            if(result.length !=0 || results.length != 0){
                console.log('email and username already exists');
                res.send({msg:"already registered with the email and username"});
            }
            else{
                con.query('INSERT INTO customers SET ?', req.body, (err, results) => {
                    if(err) throw err;
                    res.status(200).json(results);
                });
            }
        });
    });
};
//service.ts file
addCustomer (customer: Customer): Observable<Customer> {

    return this.http.post<Customer>(this.customersUrl, customer, httpOptions);
}

//create component file
addCustomer() {
    this.submitted = true;
    this.save();
}
private save(): void {
    this.customerService.addCustomer(this.customer)
        .subscribe(result=>console.log('success'));
}

【问题讨论】:

  • 将promise与then链一起使用,您可以发送成功和失败的响应。 成功 .then 和 catch 函数
  • 你能解释一下吗

标签: mysql node.js express angular6


【解决方案1】:

使用 then 链编写 api 函数。你可以在 catch 中得到错误。在成功函数和错误函数中返回您需要的任何内容。 示例:

 getQueryResults()
       .then(processResultData)
       .then((result)=>{
         return result;
       })
       .catch((error)=>{
         return error;
       });

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2019-08-08
    • 2020-06-11
    相关资源
    最近更新 更多