5

我正在使用 angular5 创建一个应用程序并表达 4.16。我在主页上有锚标记,单击应该呈现另一个组件(它应该重定向到该 URL),但只有 URL 更改。

所需的代码如下。

应用程序路由.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>

节点/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 运行 localhost:3000 后的输出作为所需的锚标记呈现

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

下载截图

测试组件.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>

项目结构

如果需要,下载项目结构

4

1 回答 1

4

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

<router-outlet></router-outlet>

然后在您的 app.routing.module.ts 中将您的主路由的对象替换为:

{ path: '', component: YourNewHomeComponent},

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

于 2017-11-11T00:51:51.017 回答