Reputation: 21
I am on a project consisting in developping a website with some APIs. I want to use js methods in typescript in order to know when the user click on the button send (send a commentary) to collect information and show them in a another section.
Here's the js code :
const express = require('express');
const mongoose = require('mongoose');
const Thing = require('./models/Thing');
mongoose.connect('mongodb+noemie_farizon://jimbob:[email protected]/test?retryWrites=true&w=majority',
{ useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('Connexion à MongoDB réussie !'))
.catch(() => console.log('Connexion à MongoDB échouée !'));
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
// middlewear pour enregister un commentaire d'utilisateur
app.post('/api', (req, res, next) => {
const thing = new Thing({
...req.body
});
thing.save()
.then(() => res.status(201).json({message: 'Objet enregistré !'}))// 201 = code création reussi
.catch(error => res.status(400).json({ error }));// 400 = code erreur
next();
});
// affichage des commentaires
app.use('/api', (req, res, next) => {
// methode en allant chercher dans la bdd
Thing.find()
.then(avis => res.status(200).json(avis))
.catch(error => res.status(400).json({ error }));
});
// pour faire les palmares des pilotes
app.use('/api', (req, res, next) => {
Thing.find()
.then(meilleur => res.status(200).json(meilleur))
.catch(error => res.status(400).json({ error }));
next();
});
module.exports = app;
and the place where i want to use these methods :
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import { Button } from 'protractor';
@Component({
selector: 'app-formulaire',
templateUrl: './formulaire.component.html',
styleUrls: ['./formulaire.component.css']
})
export class FormulaireComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
sendCommentary(){
}
}
Upvotes: 1
Views: 64
Reputation: 3243
Your question is misleading for several reasons.
I would suggest you would do a bit of investigation around how to build node express.js APIs and Angular integration. That might clarify some ideas.
Upvotes: 1
Reputation: 80
You need to separate between "Client" and "Server". Expressjs (first code snippet) is the server part, which provides the API and (probably?) hosts your Angular page (=client, second code snippet).
So there is basically no direct connection between those two applications, except the option to communicate via http(s).
You can have a look at the Angular tutorial how to implement API calls: https://angular.io/guide/http
Upvotes: 0