私はNodeJSサーバーを使用してMySQLデータベースからデータを収集し、それをJSONオブジェクトとして返します。 (ローカルホスト:3000 /ランダム)手動でURLを入力する手動リフレッシュにより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);
}
})
}
});
})
は、私が欲しいものではありませんこれは、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>
アプリ-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>
私は、サーバーを介して角度成分をレンダリングしようとすることはありませんされている問題を、知っています。私は研究を試みたが、これを行う方法を見つけることができないようだ。 012:DR:NodeJSを使用してAngularコンポーネントをレンダリングする方法を理解できないか、別の方法で考えてみることはできません。写真に示す
私の問題:
手動でURL(またはさわやかなランダムページ)を入力することにより、角度
ランダムページへのアクセスを経由用いてランダム・ページへのアクセス
APIと角URLのルート名が異なる必要があります – nmanikiran
すべてのリクエストを 'index.html'に転送する必要がありますので、角度でルーティングを処理します – YounesM
@nmanikiranありがとうございました!それが問題を解決しました。自由にそれをあなたの答えとして加えてください。私はそれを正しい答えとして受け入れることができます。 – user3510657