вызвать веб-сервис, с помощью кнопки действия с угловым, с сервера nodeJS, - PullRequest
0 голосов
/ 15 марта 2019

хочу вызвать API отдыха с сервера nodeJS одним нажатием кнопки в моем проекте angular, чтобы добавить пользователя в базу данных, API на сервере подключен к моей базе данных MySQL, просто я не буду вызывать API остальныедобавить или обновить или удалить из кнопки в моем проекте угловой.Я новичок в этом, я не знаю, как поступить.спасибо

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 голосов
/ 15 марта 2019

Предположим, что данные, которые необходимо отправить на сервер, передаются в функцию в качестве параметра «данные». Добавьте «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
          });
    }
}

Надеюсь, вышеизложенное поможет.

0 голосов
/ 15 марта 2019

Чтобы сделать вызов, вам нужно добавить HttpClientModule в ваш app.module.ts как импорт.

Затем внедрить его в 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/

...