node.js - Node/Express 角度 5 路由

标签 node.js express routing anchor angular5

我正在使用 angular5 和 express 4.16 创建一个应用程序。我在主页上有 anchor 标记,点击它应该呈现另一个组件(它应该被重定向到该 URL)但只有 URL 发生变化。

所需代码如下。

app-routing.module.ts

  import { NgModule }  from '@angular/core';
  import { RouterModule, Routes } from '@angular/router';
  import { AppComponent }   from './app.component';
  import { TestComponent }   from '../test/test.component';


  const routes: Routes = [
    { path: '', redirectTo: '/', pathMatch: 'full' },

    { path: 'Test', component: TestComponent }

  ];

  @NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
  })
  export class AppRoutingModule {}

app.component.ts

    import { Component } from '@angular/core';
    // Import the DataService
    import { DataService } from './data.service';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {  
      // Define a users property to hold our user data
      employees: Array<any>;
      // Create an instance of the DataService through dependency injection
      constructor(private _dataService: DataService) {
        // Access the Data Service's getUsers() method we defined
        this._dataService.getEmployees()
            .subscribe(res => this.employees = res);
      }
    }

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule }    from '@angular/forms';
    import { AppComponent } from './app.component';
    import {TestComponent  } from '../test/test.component';
    import { AppRoutingModule }     from './app-routing.module';
    import{DataService} from './data.service'
    import {HttpModule} from '@angular/http'
    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        AppRoutingModule,
        HttpModule
      ],
      declarations: [
        AppComponent,
        TestComponent

      ],

      providers: [DataService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

通过 ng build/dist/index.html 输出文件夹

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>IndexV3</title>
      <base href="/">

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
      <app-root></app-root>
      <test-html></test-html>
    <script type="text/javascript" src="inline.bundle.js"></script>
    <script type="text/javascript" src="polyfills.bundle.js"></script>
    <script type="text/javascript" src="styles.bundle.js"></script>
    <script type="text/javascript" src="vendor.bundle.js"></script>
    <script type="text/javascript" src="main.bundle.js"></script>
    </body>
    </html>

Node/Express server.js

            const express = require('express');
            const bodyParser = require('body-parser');
            const path = require('path');
            const http = require('http');
            const app = express();

            // API file for interacting with MongoDB
            const api = require('./server/routes/api');

            // Parsers
            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({ extended: false}));

            // Angular DIST output folder
            app.use(express.static(path.join(__dirname, 'dist')));

            // API location
            app.use('/api', api);

            // Send all other requests to the Angular app
            app.get('*', (req, res) => {

                res.sendFile(path.join(__dirname, 'dist/index.html'));
            });

            //Set Port
            const port = process.env.PORT || '3000';
            app.set('port', port);

            const server = http.createServer(app);

       server.listen(port, () => console.log(`Running on         localhost:${port}`));

根据需要输出主页

Downoad screenshot Output after running localhost:3000 as desired anchor tag rendered

点击 anchor 标记 url 后更改但测试组件未在浏览器上呈现

Downoad screenshot

test.component.ts

    import { Component } from '@angular/core';

    @Component({

      selector: 'test-html',
      templateUrl: './test.component.html'

    })
    export class TestComponent {
      title = 'app';
    }

app.component.html

    <!--The content below is only a placeholder and can be replaced.-->
    <div style="text-align:center">
      <h1>    
      </h1>  
    </div>

    <a   [routerLink]="['/Test']"  >test</a>
    <ul>
      <li *ngFor="let employee of employees">{{employee.name}}</li>
    </ul>

test.component.html

        <span>yeeee</span>

项目结构

download project structure if required

最佳答案

您缺少路由器 socket 。获取 app.component 的模板并使用该模板创建一个新组件。然后让你的 app.component.html 只包含

<router-outlet></router-outlet>

然后在您的 app.routing.module.ts 中将您的家庭路线的对象替换为:

{ path: '', component: YourNewHomeComponent },

关于路由器 socket 的更多信息:https://angular.io/guide/router#router-outlet

关于node.js - Node/Express 角度 5 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47226347/

相关文章:

javascript - 使用 Express-Handlebars View 引擎在 Express 4.x 框架中呈现局部 View

node.js - JSON 响应 : Node server and Sencha

javascript - 导航栏导致其他组件无法在 React Router 中加载

javascript - 从 NodeJS 内部调用 Express Route

ruby-on-rails - Rails Devise 路由错误 - "No route matches"( Controller = >"devise/sessions")

node.js - 安装 node.js ver 0.8 但 node --version 仍然显示以前的版本 0.6.12

javascript - Sails.js 单页应用程序 (SPA) — 将所有丢失/未使用的路由重定向到单个 Controller 操作

node.js - HTTP GET 参数未传递给 Express app.get

node.js - NodeJS Express 中间件无需 next() 即可转到下一个

c# - 如何在 asp.net MVC 中设置复杂的路由