До сих пор я мог использовать фиктивный API с помощью самого модуля HttpClient от Angular.Сейчас я пытаюсь создать бэкэнд для подачи API через Node.js.Это потому, что позже я хочу передать реальные данные приложения и сохранить их в базе данных.
У меня возникли проблемы с выяснением того, как использовать Node's http модуль.Я понимаю, что «Экспресс» существует, чтобы обернуть множество шаблонов, но мне нравится оставаться в курсе как можно больше при обучении.Позже я буду изучать Express.
Макет API обслуживает строку JSON с сайта mockapi.io.Как уже было сказано, мой интерфейсный REST API может получить данные, если напрямую вызвать макет.Но, как и сейчас, я страдаю от неправильного понимания объектов Http.ClientRequest и Http.ServerResponse в Node.
Итак, задом наперед:
Скрипт внутреннего интерфейса (узел): app.js
const request = require('request');
const http = require('http');
//returns a stream
let s = request('https://5b82c6892fd7f2001417916a.mockapi.io/mock');
let data = ''
s.on('data', (chunk) => {
data += chunk;
});
JSON.stringify(data);
s.on('end', () => {
console.log('Got data');
});
server = http.createServer((req, res) => {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
};
res.writeHead(204, headers);
res.write(data);
res.end();
});
server.listen(3500);
API REST внешнего интерфейса (Angular6) : data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'
//
import { Transaction } from '../models/transaction.model';
@Injectable({
providedIn: 'root'
})
export class DataService {
//https://5b82c6892fd7f2001417916a.mockapi.io/mock
//
baseUrl: string = 'http://localhost:3500/';
constructor(private http: HttpClient) { }
getAllTransactions(): Observable<Transaction[]> {
return this.http.get<Transaction[]>(this.baseUrl);
}
}
Служба репо, которая вызывает RESTAPI (ng6) : транзакция-respository.service.ts
import { Injectable } from '@angular/core';
//
import { DataService } from './data.service';
import { Transaction } from '../models/transaction.model';
@Injectable({
providedIn: 'root'
})
export class TransactionRepositoryService {
private transactions: Transaction[];
constructor(private dataservice: DataService) {
this.dataservice.getAllTransactions().subscribe(
(data) => { this.transactions = data; console.log('Transactions Received') },
(error) => console.log(error),
() => console.log('Repo GET request ended'));
}
getAllTransactions(): Transaction[]{
return this.transactions;
}
}
Компонент nG, вызывающий службу репо (ng6) : Transactions.component.ts
import { Component, OnInit } from '@angular/core';
import { Transaction } from '../../models/transaction.model';
import { TransactionRepositoryService } from '../../services/transaction-repository.service';
@Component({
selector: 'app-transactions',
templateUrl: './transactions.component.html',
styleUrls: ['./transactions.component.css']
})
export class TransactionsComponent implements OnInit {
private transactions: Transaction[];
private sortParam: number = 0;
constructor(private repo: TransactionRepositoryService) {
this.transactions = this.repo.getAllTransactions();
}
ngOnInit() {
}
get trans(): Transaction[] {
return this.transactions;
}
}
Шаблон этого компонента (ng6) : Transactions.component.html
<table>
<thead>
<tr>
<td>ID</td>
<td>Date/Time</td>
<td>Vendor</td>
<td>Category</td>
<td>Amount</td>
<td>Options</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let t of trans">
<td>
{{t.id}}
</td>
<td>
{{t.date}}
</td>
<td>
{{t.vendor}}
</td>
<td>
<input type="text" placeholder="category here" />
</td>
<td>
{{t.amt}}
</td>
<td>
</td>
</tr>
</tbody>
</table>
И рассматриваемая модель данных (ng6) : транзакция.model.ts
export class Transaction{
constructor(
public id: number,
public date: Date,
public vendor: string,
public amt: number,
public category?: string
){}
}
Очень ценится,