【发布时间】:2018-04-16 03:09:18
【问题描述】:
我正在使用 NodeJS 服务器从 MySQL 数据库中收集数据,并将其作为 JSON 对象返回。
app.get('/random', (req, res) => {
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test'
});
connection.connect((err) => {
if(err) {
res.send(err);
} else {
console.log("Connected to database!");
connection.query("SELECT * FROM test", (err, rows) => {
if(err) {
res.send(err);
} else {
res.json(rows);
}
})
}
});
})
手动输入 URL (localhost:3000/random) 会导致 JSON 对象呈现,这不是我想要的。
但是,使用 Angular (v4) 路由,它可以根据需要呈现 HTML,其中包含页眉、页脚和中间的数据。重要的角度代码如下所示。
random.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class RandomService {
constructor(private http: Http) {
console.log('Random service initialized!');
}
fetchData() {
return this.http.get('/random')
.map(res => res.json());
}
}
random.component.ts
import { Component, OnInit } from '@angular/core';
import { RandomService } from './random.service';
import { Random } from '../../../Random';
@Component({
selector: 'app-random',
templateUrl: './random.component.html',
styleUrls: ['./random.component.css'],
providers: [RandomService]
})
export class RandomComponent implements OnInit {
random: Random[];
constructor(private randomService: RandomService) {
this.randomService.fetchData()
.subscribe(data => {
this.random = data;
})
}
ngOnInit() {
}
}
random.component.html
<h1>Random</h1>
<div *ngFor="let r of random">
ID: {{ r.idtest }}
<br>
Column: {{ r.testcol }}
<br>
</div>
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
import { HomeComponent } from './components/home/home.component';
import { RandomComponent } from './components/random/random.component';
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'random', component: RandomComponent },
{ path: 'page-not-found', component: PageNotFoundComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
我知道这个问题,我从不尝试通过服务器渲染 Angular 组件。我已经尝试过研究,但我似乎无法找到如何做到这一点。
TL;DR:不知道如何使用 NodeJS 渲染 Angular 组件,或者想出另一种方法。
图片中显示我的问题:
【问题讨论】:
-
API 和 Angular url 路由名称应该不同
-
您应该将所有请求转发给
index.html,这样它就可以让 Angular 处理路由 -
@nmanikiran 谢谢!这解决了这个问题。随意添加它作为你的答案,所以我可以接受它作为正确的答案。
标签: mysql json node.js angular express