表单字段未使用mongodb和nodejs更新到数据库Angular

时间:2018-02-18 19:11:40

标签: node.js angular mongodb

我正在尝试创建联系人应用程序,用户可以将联系人信息保存到数据库。这里表单数据没有更新到数据库,而如果我使用邮递员手动更新数据,它工作正常。删除功能和获取联系人功能完美正常。只有问题是addContact()。

但是,按下提交按钮后,我看不到任何控制台错误。

我使用MongoDB作为数据库,nodejs作为服务器端,angular2作为前端接口。

contact.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Contact} from './contact';
import 'rxjs/add/operator/map';


@Injectable()
export class ContactService {

  constructor(private http:Http) { }

  getContacts()
  {
    return this.http.get('http://localhost:3000/api/contacts')
    .map(res=>res.json());
  }

  addContact(newContact)
  {
    var headers = new Headers();
    headers.append('Content-Type','applicaiton/json');
    console.log("I am working fine");
    return this.http.post('http://localhost:3000/api/contact', newContact, {headers:headers})
    .map(res => res.json());
  }

  deleteContact(id)
  {
    return this.http.delete('http://localhost:3000/api/contact/'+id)
    .map(res=>res.json())
  }


}

contacts.component.ts

  import { Component, OnInit } from '@angular/core';
  import {ContactService} from '../contact.service';
  import {Contact} from '../contact';


  @Component({
    selector: 'app-contacts',
    templateUrl: './contacts.component.html',
    styleUrls: ['./contacts.component.css'],
    providers:[ContactService]
  })
  export class ContactsComponent implements OnInit {

  contacts: Contact[];
  contact:Contact;
  first_name:string;
  last_name:string;
  phone: string;

    constructor(private contactService: ContactService) {}

    addContact(){
        const newContact = {
            first_name: this.first_name,
            last_name : this.last_name,
            phone: this.phone
        }
        this.contactService.addContact(newContact)
        .subscribe(contact=>{this.contacts.push(contact);
       this.contactService.getContacts() .subscribe( contacts => this.contacts = contacts);
        })

    }

    deleteContact(id:any){
        var contacts = this.contacts;
        this.contactService.deleteContact(id)
        .subscribe(data=>{
            if(data.n==1) {
                for(var i=0; i<contacts.length; i++) {
                    if(contacts[i]._id == id) {
                        contacts.splice(i,1);
                    }
                }
            }
        })
    }
    ngOnInit() {
        this.contactService.getContacts()
        .subscribe( contacts => 
            this.contacts = contacts);
    }

  }

contacts.component.html

    <div class="container">
    <h2 class="page-header">Add Contact</h2>
    <form (submit)="addContact()">
        <div class="form-group">
            <label for="first_name">First Name</label>
            <input type="text" [(ngModel)]="first_name" name="first_name" class="form-control">
        </div>
        <!-- /.form-group -->
        <div class="form-group">
            <label for="first_name">Last Name</label>
            <input type="text" [(ngModel)]="last_name" name="last_name" class="form-control">
        </div>
        <!-- /.form-group -->
        <div class="form-group">
            <label for="first_name">Phone</label>
            <input type="text" [(ngModel)]="phone" id="phone" name="phone" class="form-control" required>
        </div>
        <!-- /.form-group -->
        <div class="form-group">
            <input type="submit" class="btn-btn-success" value="Add Contact">
        </div>
        <!-- /.form-group -->

    </form>
    <hr>
    <div class="row" *ngFor="let contact of contacts">
        <div class="col-lg-3">
            {{contact.first_name}}
        </div>
        <div class="col-lg-3">
            {{contact.last_name}}
        </div>
        <div class="col-lg-3">
            {{contact.phone}}
        </div>
        <div class="col-lg-3">
            <input type="button" (click)="deleteContact(contact._id)" value="Delete" class="btn btn-danger">
        </div>
    </div>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
</div>

请帮我调试我的代码。 提前致谢。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

你的问题是这一行。

<div class="form-group">
            <input type="submit" class="btn-btn-success" value="Add Contact" onSubmit($event)>
 </div>

你需要在其上放置一个处理程序,以便angular知道你想要发送http调用。

<?php

    $lat = $_POST['latitude'];
    $long = $_POST['longitude'];

    require_once $_SERVER['DOCUMENT_ROOT'].'/assets/php/database/main.php';

    $sql='select message, x(msg_location), y(msg_location), loved 
        from hidyn_msg where 3963 * acos(
        sin(radians(x(msg_location))) * sin(radians(x(msg_location))) + cos(radians(x(msg_location)))  * cos(radians(:lat)) * cos(radians(:long) - radians(:long))) <= 10
        order by msg_date desc';

        $stmt = $conn->prepare( $sql );
        $stmt->bindParam(':lat', $lat);
        $stmt->bindParam(':long', $long);

        try{
            $stmt->execute();
            $results = $stmt->fetchAll( PDO::FETCH_ASSOC );
            if(count($results) > 0):
                echo json_encode($results);
            endif;
        }catch(Exception $e){
            $stmtError = $stmt->errorInfo();
            $statusMSG= array('error'=>false, 'message' => "We had a issue creating and posting your message. Error: ", $e[0]);
            echo json_encode(statusMSG);
        }
?> 

然后对于onSubmit,您可以使用发出的事件发送呼叫。