通过来自nodeJS服务器的带有angular的动作按钮调用Web服务,

时间:2019-03-15 11:04:12

标签: node.js angular rest api

想要从nodeJS服务器中调用rest API,只需在我的项目中单击一个按钮即可在数据库中添加用户,服务器中的api已连接到我的mysql数据库,而我不会调用api rest从我的项目角的按钮中添加或更新或删除。我是新来的,我不知道如何进行。 谢谢

import { Component } from '@angular/core';
import { LocalDataSource } from 'ng2-smart-table';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SmartTableData } from '../../../@core/data/smart-table';
//import { EmailValidator } from '@angular/forms';


@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
}

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './smart-table.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
  `],
})

@Injectable()
export class Configuration {
    public server = 'http://localhost:3000/';
    public apiUrl = 'api/';
    public serverWithApiUrl = this.server + this.apiUrl;
}



export class SmartTableComponent {

  settings = {
    add: {
      addButtonContent: '<i class="nb-plus"></i>',
      createButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      actionButonContent:'<i (click)="makeServiceCall($event)"><i/>',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      actionButonContent:'<i (click)="onEditConfirm($event)"></i>'
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
      actionButonContent:'<i (click)="onDeleteConfirm($event)"></i>'
    },
    columns: {
      id: {
        title: 'ID',
        type: 'number',
      },
      firstName: {
        title: ' Name',
        type: 'string',
      },
      email: {
        title: 'E-mail',
        type: 'string',
      },
      password: {
        title: 'password',
        type: 'password',
      },
    },
  };
  source: LocalDataSource = new LocalDataSource();
  constructor(private service: SmartTableData) {
    const data = this.service.getData();
    this.source.load(data);
  }
  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }
}

这是我的app.js(服务器)

 var express = require('express');
 var router = express.Router();
 var user=require('../model/user');

router.get('/:id?',function(req,res,next){


if(req.params.id){

user.getUserById(req.params.id,function(err,rows){

if(err)
  {
  res.json(err);
  }
  else{
  res.json(rows);
  }
  });
 }
 else{

user.getAllUsers(function(err,rows){

if(err)
  {
  res.json(err);
  }
  else
  {
  res.json(rows);
  }

 });
 }
 });
 router.post('/',function(req,res,next){

user.addUser(req.body,function(err,count){
  if(err)
  {
  res.json(err);
  }
  else{
  res.json(req.body);
  }
  });
 });
 router.delete('/:id',function(req,res,next){

user.deleteUser(req.params.id,function(err,count){

if(err)
  {
  res.json(err);
  }
  else
  {
  res.json(count);
  }

});
 });
 router.put('/:id',function(req,res,next){

user.updateUser(req.params.id,req.body,function(err,rows){

if(err)
  {
  res.json(err);
  }
  else
  {
  res.json(rows);
  }
  });
 });

 module.exports=router;

2 个答案:

答案 0 :(得分:0)

要进行呼叫,您需要在app.module.ts中将HttpClientModule添加为导入。

然后将Http客户端注入到您想使用它的任何地方:

constructor(private http: HttpClient){}

要使用它,只需执行以下操作:

this.http.get(<<url>>) //for get request this.http.post(<<url>>,obj) //for post request 这将返回一个可观察的对象,您可以使用该对象映射结果并使用Rxjs运算符捕获错误。例如

addUser(user){ //called on button click
    this.http.post(yourUrl,Json.Stringify(user)).pipe(
      map((res)=>{
         //do something with response
         return 'sucess'
        }),
      catchError(err => {
        //handleError
      }
    ).subscribe(); // dont forget to subscribe
    }

如果您想了解更多信息:https://angular.io/guide/http 对于rxjs:https://www.learnrxjs.io/

答案 1 :(得分:0)

假定需要发送到服务器的数据作为“数据”参数传递给函数。将“ HttpClientModule”添加到主应用程序模块或自定义模块(如果有),如下所示。自定义服务已导入到应用程序模块中,或已相应地导入到您的模块中。

app.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { CustomService } from 'location-of-custom-service';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpClientModule
  ],
  declarations: [],
  providers: [CustomService]
})

export class AppModule { }

按如下所示创建服务文件。

custom.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class CustomService {

   public server = 'http://localhost:3000/';
   public apiUrl = 'api/';
   public serverWithApiUrl = this.server + this.apiUrl;

   private fetchDataURL = this.serverWithApiUrl + 'fetchSomeData'; 
   private addDataURL = this.serverWithApiUrl + 'addSomeData' 


  constructor(private _http: HttpClient) { }

  // Fetch data
  fetchData(id): Observable<any> {
    this.fetchDataURL = this.fetchDataURL + "/" + id;
    return this._http.get<any>(this.fetchDataURL, httpOptions)
     .pipe(
        retry(1),
        catchError(this.handleError)
     );
  }

  // Add data
  addData(data): Observable<any> {
    return this._http.post<any>(this.addDataURL, data, httpOptions);
  }

 // Error handler - you can customize this accordingly 
 handleError(error) {
   let errorMessage = '';
   if (error.error instanceof ErrorEvent) {
     // client-side error
     errorMessage = `Error: ${error.error.message}`;
   } else {
     // server-side error
     errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
   }
   return throwError(errorMessage);
 }
}

您现有的组件已被修改,以便具有如下新增功能。

smarttable.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { CustomService } from './custom-service-location';

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './smart-table.component.html'
})

export class SmartTableComponent  implements OnInit {

    constructor(private customService: CustomService) {}
    fechedData: any;

 // you existing codes goes here

    // Add data - assume the data that needs to be sent to the server is as "data"
    makeServiceCall(data) {
        this.customService.addData(data)
          .subscribe((data) => {
            console.log(data);
            // your logic after data addition goes here
          },
          (error) => {
              // logic to handle error accordingly
          });
    }

    // Fetch data
    getData(id) {
        this.customService.fetchData(id)
          .subscribe((data) => {
            console.log(data);
            this.fechedData = data;
            // your logic after data fetch goes here
          },
          (error) => {
              // logic to handle error accordingly
          });
    }
}

希望以上内容对您有所帮助。